我有一个在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'})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句