【问题标题】:Cannot send object in post request无法在发布请求中发送对象
【发布时间】:2025-12-25 19:55:11
【问题描述】:

我想在 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));
});

然后我在开发工具/控制台中得到这个:

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

谁能帮帮我?

【问题讨论】:

    标签: node.js vue.js express


    【解决方案1】:

    您必须解析正文,这可以通过使用: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);
    },
    

    【讨论】:

    • 我的后端已经有了这条线:/
    • @LabodaDániel 我改变了我的答案。我不清楚你在哪里谈论前端或后端。我的借口。
    • .then((res) => {return res.json()}).then((json) => {console.log(json)}) 可以分别是.then((res) => res.json())` 和then(console.log)
    • @jub0bs 是的,但我认为这超出了这个问题的范围。
    • 现在我收到此错误消息:Uncaught (in promise) SyntaxError: Unexpected end of JSON input