Fetch post with body data not working params empty

Followed this topic on github: https://github.com/matthew-andrews/isomorphic-fetch/issues/34

The solution to my question is using the JSON.stringify function and set Content-Type header to application/json. Not pretty sure why the second attempt in my question didn't work though.

fetch('/api/v1/users', {  
    method: 'post',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ "user": {
      "email" : email,
      "password" : password
    }}),
})

Official MDN Documentation:

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');

fetch('/contact-form', {
    method: 'POST',
    headers: myHeaders,
    mode: 'cors',
    cache: 'default',
    body: JSON.stringify(fields)
}).then(() => {
    dispatch(contactFormSubmitSuccess());
});

headers: {'Content-Type': 'application/json'}

already answered


TL;DR Without mode: 'cors' your JSON body won't go through.

I wrestled with this for a bit. cors was the issue. Assuming you are performing a request from one domain to another (i.e. from localhost:8080 to localhost:3000) you need to have mode: 'cors' in the fetch settings & your receiving domain (localhost:3000) needs to allow requests from the sending domain (localhost:8080).

So the above description in code:

request from localhost:8080 to localhost:3000

fetch('http://localhost:3000/users/sign_in', {
      method: 'POST',
      mode: 'cors', // this cannot be 'no-cors'
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        "user": {
          "email": `${this.state.userEmail}`,
          "password": `${this.state.userPass}`
        }
      }),
    })

And then make sure your receiving domain localhost:3000 allows CORS from localhost:8080.


worked in this way when sending body as json failed.

        var formData = new FormData();
        formData.append('key1', 'value1');
        formData.append('key1', 'value2');

        fetch('url', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data'
            },
            body: formData
        }`)`

EDIT: In my case, the server only identified the content through the form-data submission. The code was not written to read the request body as json. So there is a possibility to have an issue with your server side code as well.

Tags:

Ajax

Fetch