Fetch: Empty POST body

Created on 28 Apr 2016  ·  17Comments  ·  Source: github/fetch

Hello i'm using Fetch on Node with React and Browserify, i trigger this code from a form submit:

event.preventDefault();

var form = new FormData();
form.append('a', 1);

fetch('http://localhost:8080/login', {
      method: 'POST',
      body: form
})

Can't figure out why the request sent to the server has empty body, no matter what i put in (i also tried strings as body).

Any ideas?

Most helpful comment

Thanks guys, saved me a day. Essentially, what did work out for me:
Client: fetching with headers: { "Content-Type": "application/json" }
Server: adding app.use(require("body-parser").json())

All 17 comments

Where is this code executing? On the server (with node.js) or in a browser? If in a browser, which one? Is the HTTP request to another host name or port number? If so, it's subject to CORS policies.

Hi, the code is executing in the browser (Chrome). The request is sent to the server that host the app, same host name, same port number.

Your usage of fetch looks alright. How are you verifying that the HTTP request doesn't have a POST body? Did you try right-clicking in Developer console and choose “Log XMLHttpRequest”?

Closing since this is related to Chrome, which does not use this polyfill, but feel free to continue discussing the issue.

Huh, I'm having the same issue. The request appears to be successful, but the body is empty.

I am using Chrome and my request looks like this:

    const data = {
      email: "[email protected]"
    }

    fetch('http://localhost:3030/api/purchase', {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    }).then((res) => {
      console.log("this is res", res)
    }).catch((err) => {
      console.log(err)
    })

The XMLHttpRequest appears to have been successful:

index.js:63 Fetch complete: POST "http://localhost:3030/api/purchase".

I have a simple logger that logs the request and response.body:

{}
POST to /api/purchase
took 1 ms

I've tried it with import 'whatwg-fetch' and without.

When I run the request with Ajax, it works properly:

        $.ajax({
          type: 'POST', url: 'http://localhost:3030/api/purchase', data: {
            email: "[email protected]"
          },
        }).done(function(res) {
          console.log(res);
        })

I had the same problem. I solved using:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

every body is suggesting the same solution as of @madsilver but unfortunately this isn't working at my end.
Any success by using fetch?

@m-adil You might forgot to add contenttype in the request header

has anyone had success resolving this issue ?

I had the same issue and I solved it. First you have to fix the cross browser issue by doing something like this on your api server (I'm using node with Express):

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Second, you have to make sure you are able to parse json by doing something like this on your api server:

`app.use(require("body-parser").json());
`

Note that you rarely send x-www-form-urlencoded data with react, because the recommended way of posting form data it is not by using the form directly, but by setting up a form handler. That is why it doesn't work via react, but it does work with Postman, Curl or some other test-tool.

Thanks guys, saved me a day. Essentially, what did work out for me:
Client: fetching with headers: { "Content-Type": "application/json" }
Server: adding app.use(require("body-parser").json())

it might be not that obvious but make sure you are doing app.use(bodyParser.json()); before registering your routes!

Adding header with content-type key solved it! Thanks!

Hi,

I am facing the same issue since a week. I have tried lots of things to resolve it :(
Since its as it is, Can anyone help me out for the issue why I am not able to call my API with fetch but able to call it using postman?

Below is my code for further reference, I have enable CORS at server side where I have made my API.
The APIs are build in ASP dotnet core.

Both API and react project is running in my localhost if I try to call that API using postman than its working with same parameter but its not working with fetch,

NOTE: If I set [AllowAnonymous] in my API than it give me response as expected and same as postman.
But I want the functionality which must be authenticated the key passed by client and than return the JWT token to client.

I am tired now please help me out if anyone have solutions for same.

var param={
grant_type: 'password',
username: 'username',
password: 'password'
};

var formData = [];
for (var property in param) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(param[property]);
formData.push(encodedKey + "=" + encodedValue);
}
formData = formData.join("&");

   let headers2 = new Headers();          
   headers2.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
   headers2.append('AuthServerKey', 'AUTHENTICATIONKEY');

fetch(URL, {
mode:'cors',
method: 'post',
withCredentials: true,
crossdomain: true,
headers: headers2,
body: formData
}).then(function(response) {
alert(response);
if (response.status >= 400) {
throw new Error("Bad response from server");
}
response.json().then(function(data) {
console.log(data);
});
//console.log(response);
//return response.json();
}).catch(err => {
console.log('caught it!',err);
})

Thanks

Thanks Guys. I had the same problem. The solution from @Piepongwong solved my problem.
I had the same problem where the response.body was an empty object.
The console showed the following error on posting something from React to my express server:
image

I have the following on my server.js file:
app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); var bodyParser = require('body-parser') app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true }))

Client side looks like below:
var resp = await fetch('http://localhost:5000/order', { method: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(order) }) .then(function(response) { return response.json(); });

At the time of the post i solved using node-fetch package instead of this one.

'Content-Type': 'application/x-www-form-urlencoded',

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sndsgn picture sndsgn  ·  3Comments

ccorcos picture ccorcos  ·  3Comments

xgqfrms-GitHub picture xgqfrms-GitHub  ·  4Comments

naivefun picture naivefun  ·  3Comments

mmocny picture mmocny  ·  3Comments