1

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

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)

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?

antzshrek
  • 9,276
  • 5
  • 26
  • 43
Aryan
  • 103
  • 1
  • 1
  • 8

3 Answers3

3

You are using the wrong Content-Type to send json

Try

"Content-Type": "application/json;charset=UTF-8"
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

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, i.e. 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; charset=utf-8” really mean?

antzshrek
  • 9,276
  • 5
  • 26
  • 43
0

The problem is that you are stringifying the data:

body: JSON.stringify(data)

should be

body: data

That should fix it

Mikkel
  • 7,693
  • 3
  • 17
  • 31