Search code examples
ajaxfetch

Fetch post with body data not working params empty


I am trying to rewrite my ajax call to fetch:

Ajax:

  $.post({
    context: this,
    url: "/api/v1/users",
    data: { 
      user: 
        {
          email: email,
          password: password
        } 
    }
  }).done((user) => {
  }).fail((error) => {
  })

Fetch:

  fetch('/api/v1/users', {  
  method: 'POST',
  headers: {
    "Content-Type": "application/json"
  },      
    body: { 
    "user" : 
      {
        "email" : email,
        "password" : password
      } 
  }
  })
  .then(res => {  
    if (res.status !== 200) { {
        console.log("error")
      })          
    } else {
      res.json().then(data => {
        console.log(data)
      })
    }
  })

I am getting an error empty params ~ bad request from my server.

I also found this way to do it, but in this code below I am getting an error: Unexpected token.

  var payload = { 
    "user" : 
      {
        "email" : email,
        "password" : password
      } 
  };

  var data = new FormData();
  data.append( "json", JSON.stringify( payload ) );

  fetch('/api/v1/users', {  
  method: 'POST',
  headers: {
    "Content-Type": "application/json"
  },      
    body: data
  })

How can I rewrite the ajax request to fetch?


Solution

  • 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());
    });