我想在post请求中从后端发送一个对象到前端。我得到了前面的对象,但是里面没有数据。
这是我在前端的功能(Vue 3):
backend2(e){
e.preventDefault();
fetch('http://localhost:5000/enemystrongest', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({enemyCards: this.enemysCards})})
.then((res) => {return res})
.then((res) => {console.log(res)})
},这是我的后端root.js (NodeJS):
router.post('/enemystrongest', (req, res, next) => {
let cards = req.body;
res.setHeader("Content-Type", "application/json")
res.send(findEnemyStrongest(cards));
});然后,我在dev tool/console中得到了这样的信息:
Response {type: 'cors', url: 'http://localhost:5000/enemystrongest', redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:5000/enemystrongest"
[[Prototype]]: Object有谁可以帮我?
发布于 2022-01-05 18:28:55
您必须解析主体,这可以通过使用:res.json()来完成(这将返回一个承诺)
backend2(e){
e.preventDefault();
fetch('http://localhost:5000/enemystrongest', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({enemyCards: this.enemysCards})})
.then((res) => {return res.json()})
.then((json) => {console.log(json)}) // as @jub0bs said this can be shortend as .then(console.log);
},https://stackoverflow.com/questions/70597804
复制相似问题