用ajax向express后台发post请求,接收到的req.body为什么是空对象?

前端js:

regBtn.onclick = function () {
  let userjson = {
    "id": input3.value,
    "password": input4.value
  };
  
  const xhr = new XMLHttpRequest();
  xhr.open('post', '/login');
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
  xhr.send(userjson);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status >= 200 && xhr.status < 300) {
        console.log(xhr.response);
        //之后要根据不同的response进行不同的操作
      }
    }
  }
}

后端:

app.post('/login', function (req, res) {
  console.log(req.body); // 空对象
});

请问是出了什么问题呢

补充:
现在知道我ajax send的数据格式不对,改成了这样:

  xhr.send(`id=${input3.value}&password=${input4.value}`);

但是还存在空对象问题...

我又加上了

  xhr.setRequestHeader("Content-Type","application/json");

结果报错:

SyntaxError: Unexpected token i in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError

解决了,改成

  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

就好了

阅读 4.2k
1 个回答

你需要添加配置解析表单请求体


// 配置解析表单请求体,类型为:application/app
app.use(express.josn())

// 解析表单请求体,类型为:application/x-www-form-urlencoded
app.use(express.urlencoded())
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题