使用ajax对象通过post传递参数为什么参数为空?

这JavaScript的代码
            var params = 'username='+ nameValue +'&age=' + ageValue;
            // 配置ajax对象
            xhr.open('post', 'http://localhost:3000/post',true);
            // 设置请求参数格式的类型(post请求必须要设置)
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            console.log(params)
            // 发送请求
            xhr.send(params);
            // 获取服务器端响应的数据
            xhr.onload = function () {
               console.log(xhr.responseText)
            }
这是服务器中的代码
app.post('/post', (req, res) => {
    res.send(req.body);
});
服务器中显示{},什么都没传进来,但是在网页中查看post参数中的form data 是有值的!

image

阅读 3.8k
2 个回答

试下JSON呢:

var params = {
    'username': 'jack ma',
    'age': 26
};

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(params));

post数据有没有配置body-parser

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题