Faktor 10
Faktor 10

Reputation: 1888

fetch method not posting as expected, compared to jQuery ajax post method

I am eager to use the new fetch method and I understand it can be used for all http method calls to a Rest endpoint.

So I have the following very simple API endpoint which I know works, get and post requests work. The issue I am having is getting the post request to work on the fetch method.

My code for the fetch method is

        var ingredient = {
      'name': 'Salt',
    }; // a JSON object used as the body for the post request

    fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
    {
      method: "POST",
      body: JSON.stringify( ingredient )
    })
    .then(function(res){ console.log( 'Data posted') })

I then get the following error message. 422 (Unprocessable Entity) enter image description here

If on the other hand I do something very similar but this time using the classic jQuery ajax post method it works.

    $.ajax({
      url: 'http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
      type: 'POST',
      data: 'name=Salt', // or $('#myform').serializeArray()
      success: function() { console.log('Data posted'); }
    });

enter image description here

Any help here would be appreciated, it feels like I am missing something small here, and documentation on fetch method is scant on the web.

Upvotes: 3

Views: 1325

Answers (1)

Musa
Musa

Reputation: 97707

The two request sends two different post bodies one is application/x-www-form-urlencoded (jQuery) and the other is application/json.
You'll have to change the fetch call to send the same type of data as the $.ajax call.
You may have to explicitly set the content type in the fetch request.

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var searchParams = new URLSearchParams();
searchParams.append("name", "Salt");
fetch('http://pantler-180711.nitrousapp.com/api/v1/Ingredients',
{
  method: "POST",
  headers: myHeaders,
  body: searchParams
})
.then(function(res){ console.log( 'Data posted') })

Upvotes: 4

Related Questions