获取请求中的正文为空

问题描述 投票:0回答:1

前端:

 fetch(location.href, {
  method: "POST",
  headers: {
    "Content-type": "application/json"
  },
  body: JSON.stringify({
    user: document.getElementById("user").innerText,
    call: "Upvote",
    cname: "comp_name"
  })
},(data) => {
  console.log(data)
})

后端:

router.post("/",(req,res) =>{
    console.log(req.body)
}

console.log 的响应只是 {} 而不是 json 数据

我也尝试记录整个响应,但正文仍然是空的,我还尝试通过将其放入变量中然后执行获取来检查 JSON.stringify 中可能引起的任何错误,但它没有帮助

javascript node.js fetch
1个回答
0
投票

实现你想要的方式,需要在服务器上添加body parser中间件,然后就可以从前端发送对象了。

这里我们导入 body-parser 并将其用作中间件。在这里您可以看到如何解析 application/x-www-form-urlencoded (表示表单数据)。然后你就可以看到如何解析json:

bodyParser.json()

注意:我在路由本身之前添加了中间件。

var bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

router.post("/",(req,res) =>{
    console.log(req.body)
}

别忘了做:

npm i body-parser

现在在前端你可以这样做:

 fetch(location.href, {
  method: "POST",
  headers: {
    "Content-type": "application/json"
  },
  body: {
    user: document.getElementById("user").innerText,
    call: "Upvote",
    cname: "comp_name"
  }
},(data) => {
  console.log(data)
})
© www.soinside.com 2019 - 2024. All rights reserved.