如何解决如何使用 MERN Stack 从 POST 请求中获取 response.status
我正在尝试获取在 POST 请求后从服务器返回的状态。元素创建正确,但即使没有“if”检查也没有响应。
这是 ReactJS 中的请求:
fetch('http://localhost:5000/products/create',{
method: 'POST',headers: {
'Content-Type': 'application/json'
},body: JSON.stringify(product)
})
.then((response) => {
if(response.status === 201) {
console.log('created')
}
})
.catch(error => console.log(error.response))
这里是服务器端:
router.post('/create',(req,res) => {
productService.create(req.body).then(() => res.status(201)).catch(() => res.status(500).end())
})
解决方法
可以尝试将状态 201 改为 200 吗?!
,试试这个,
router.post('/create',async (req,res) => {
try {
const result = await productService
.create(req.body)
.then((r) => r)
.catch((e) => {
throw e;
});
return res.status(201);
} catch (error) {
return res.status(500).end();
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。