首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在post请求中发送对象

无法在post请求中发送对象
EN

Stack Overflow用户
提问于 2022-01-05 18:22:34
回答 1查看 158关注 0票数 2

我想在post请求中从后端发送一个对象到前端。我得到了前面的对象,但是里面没有数据。

这是我在前端的功能(Vue 3):

代码语言:javascript
复制
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):

代码语言:javascript
复制
router.post('/enemystrongest', (req, res, next) => {
    let cards = req.body;
    res.setHeader("Content-Type", "application/json")
    res.send(findEnemyStrongest(cards));
});

然后,我在dev tool/console中得到了这样的信息:

代码语言:javascript
复制
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

有谁可以帮我?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-05 18:28:55

您必须解析主体,这可以通过使用:res.json()来完成(这将返回一个承诺)

代码语言:javascript
复制
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);
},
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70597804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档