在 express 中获取 post 请求参数时会返回 {} 或者 undefined
问题原因: Express默认只支持json
与x-www-form-urlencoded
格式的数据.
解决办法:
在请求中需要设置Content-type
为application/x-www-form-urlencoded
init();
function init() {
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', readystatechangeHandler);
xhr.open('post', 'http://localhost:3000/users/login');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send('a=10&b=20');
}
function readystatechangeHandler() {
if (this.status === 200 && this.readyState === 4) console.log(JSON.parse(this.response));
}
然后在服务端需要下载一个解析的中间件 body-parser
// 引入
var app = require('express');
var bodyParser = require('body-parser');
// 使用中间件
app.use(bodyParse.json()) // 支持 json 格式
// 使用第三方插件 qs 来处理
app.use(bodyParse.urlencoded({extended : true}))
// post 请求
app.post("/users/login", function(req, res) {
console.log(req.body); // 这样就可以获取 post 的参数了
});