无法访问nodejs / express中的请求正文数据

Cannot access request body data in nodejs / express

我在 nodejs/express 中设置了这样的路由:

const testSync = (req, res) => {
                  res.status(200).send(req.body.url)
                       }

 router.post('/test-sync', testSync);

在我的客户端中,我使用 fetch 发出 api 请求,如下所示:

   const requestOptions = {
        method: 'POST',
        redirect: 'follow',
        body: {
                 url: "some url"
              }
  };

  fetch(`http://${domainName}/api/test-sync`, requestOptions)
    .then(response => response.text())
    .then(result => {
          console.log(result)
    })
    .catch(error => {
            console.log(error)
    });

我这样做是为了测试如何使用请求正文数据。直到现在,如果我在邮递员上使用这个 api 端点,我只会得到一个空的 json。如果我想访问请求体数据,我应该怎么做?就像我代码中的 req.body.url

假设您使用的是 Express?你可以把它放在你的路由器里。

router.use(express.json());

对于您客户的请求,您可以尝试:

const requestOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({url: 'someurl'})
}