Search code examples
jqueryjquery-3

Unsupported Media Type when Posting JSON data to API using JQuery


I am posting data to an API using JQuery 3 as follows:

$.post({ url: "api/questions", data: { content: "Content" }, dataType: "json" })
  .done(function (data, status, xhr) {
    console.log(message);
  })
  .fail(function (xhr, status, error) {
    console.log(error);
  })

When I run it I get the following error:

Unsupported Media Type

I am not sure why this happens. I tested my API using PostMan to send a Post request with the following Body:

{
  content: "Content"
}

And it worked fine ... What am I missing?


Solution

  • Try using this:

    $.postJSON = function(url, data, callback) {
        return jQuery.ajax({
        headers: { 
            'Accept': 'application/json',
            'Content-Type': 'application/json' 
        },
        'type': 'POST',
        'url': url,
        'data': JSON.stringify(data),
        'dataType': 'json',
        'success': callback
        });
    };
    

    (taken from this answer)