向服务器发送请求时,节点没有收到req.body 可能是什么错误?
反应:
sendRequest('POST','http://127.0.0.1:5500/api/auth/register', {...form})
function sendRequest(method:string, url:string, bodyObj:any = null){
return fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyObj)
}).then(response => response.json())
.then(result => result)
}
节点:
router.post('/register',async (req,res)=>{
console.log(req.body)
res.status(200).json(req.body)
})
答案 0 :(得分:0)
这里发生的一些事情可能会导致问题,但我认为要调查的主要领域是 sendRequest
函数正在返回一个异步的 Promise,但它也在尝试 .then
相同的功能。
在要处理数据的地方解析或拒绝返回承诺可能是更好的执行。
// This returns a Promise
function sendRequest(method, url, bodyObj) {
return fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyObj)
})
}
sendRequest('POST', 'http://127.0.0.1:5500/api/auth/register', { ...form
}).then(result => {
console.log(result)
}).catch(err => {
console.log(err)
})