Express req主体始终为空

时间:2019-08-09 12:40:11

标签: node.js api express

我正在尝试使用Express创建新的POST方法路由。此路由将接收JSON中的数据。为此,我初始化了Express应用程序:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('dist'));

app.post('/api/getUsername', (req, res) => {
  console.log(req.headers); // Correct headers from client side
  console.log(req.body); // Empty object {}
  res.status(200).send();
});

app.listen(8080, () => console.log(`Listening on port ${8080}!`));

在客户端,我使用fetch API发送数据:

  await fetch('http://localhost:8080/api/getUsername', {
    mode: 'no-cors',
    headers:{
      'Access-Control-Allow-Origin':'*',
      'Content-Type': 'application/json',
      'Cache-Control': 'no-cache'
    },
    method: 'POST',
    body: JSON.stringify({ hello: 'world' })
  });

但是我在服务器端的req.body总是空的。

有人可以帮助我吗?

谢谢社区!

1 个答案:

答案 0 :(得分:0)

 await fetch(http://localhost:8080/api/getUsername', {
    method: 'POST',
    headers: {
      'Access-Control-Allow-Origin':'*',
      'Content-Type': 'application/json',
      'Cache-Control': 'no-cache'
    },
    body: JSON.stringify({hello: 'world'})
  });