简体   繁体   English

通过fetch()向后端API发送POST请求时,主体只有键,没有值

[英]When sending POST request to backend API via fetch(), the body has only key and no value

When I'm sending a POST request to my backend express server, the req.body contains only the key part where the entire body is the key and the value part is empty 当我向后端Express服务器发送POST请求时, req.body仅包含关键部分,其中整个主体是关键,而值部分为空

This is the frontend fetch request 这是前端获取请求

let data = {
  videoUrl: "dummy text"
}
fetch("/api/getinfo", {
  method:"POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  },
  body: JSON.stringify(data)
})

This is how I handle it in backend ( NOTE : I'm using body-parser ) 这就是我在后端处理的方式( 注意 :我正在使用body-parser

app.post("/api/getinfo", (req,res) => {
    console.log(req.body);
}

I expect the output to be 我希望输出是

'{ "videoUrl":"dummy text" }'

But what I get is 但是我得到的是

{ '{"videoUrl":"dummy text"}': '' }

The entire requests body is the key, and the value is empty. 整个请求主体是键,值是空的。

What am I doing wrong? 我究竟做错了什么?

You are using the wrong Content-Type to send json 您使用了错误的Content-Type发送json

Try 尝试

"Content-Type": "application/json;charset=UTF-8"

I noticed an issue in your header ; 我注意到您的标题中有一个问题;

fetch("/api/getinfo", {
  method:"POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" //this very line
  },

I guess what you meant is 我想你的意思是

fetch("/api/getinfo", {
  method:"POST",
  headers: {
    'Content-type': 'application/json; charset=utf-8'
  },

Note : Your header denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, ie you can't necessarily just look at the content and know what to do with it. 注意 :标头指示内容的编码内容。不一定可以从内容本身推断出内容的类型,即,您不必仅查看内容并知道如何处理。 So you need to be sure of what you're writing in your header else you will end up with an error. 因此,您需要确定标头中正在写的内容,否则最终将出现错误。

I will suggest you get to read more about What does “Content-type: application/json; 我建议您阅读更多有关“内容类型:application / json; charset=utf-8” really mean? charset = utf-8”真的是什么意思?

The problem is that you are stringifying the data: 问题是您正在对数据进行字符串化:

body: JSON.stringify(data)

should be 应该

body: data

That should fix it 那应该解决它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM