Callback success not called with status code 201

I am working with the Rest API. I would like to create a ressource with AJAX and jQuery . My ressource is created correctly, but the error callback is being called.

My code is:

$.ajax({ url: "/api/skills.json", data: JSON.stringify(skill), method: "POST", contentType: "application/json", statusCode: { 201: function (data) { console.log("201"); } }, success: function (data) { console.log("success"); }, error: function (data) { console.log("error"); }, complete: function (data) { console.log("complete"); } }); 

Result in the "Network" from the Firefox console:

 HTTP/1.1 201 Created Date: Thu, 27 Oct 2016 08:29:08 GMT Server: Apache X-Powered-By: PHP/7.0.8 Cache-Control: no-cache Location: http://localhost/api/skills/pdak12ada64d Allow: POST Content-Length: 0 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: application/json 

And the result from the console:

 "201" "error" "complete" 

Why does jQuery call an error callback with status 201?

I tried using the shortcut $.post method and the same result, I do not use the shortcuts method, because I use custom headers.

+5
source share
1 answer

As mentioned in my comment above, it seems that when jQuery.Ajax gets an empty response and tries to parse it as JSON, it throws an error, which is then interpreted as an error with the answer (and not parsing it).

This means that you have two options: either send the request as text and not JSON (which I would not recommend) or process the answers using statusCode , as you do in the question, and remove the success and error callbacks.

Link: fooobar.com/questions/537008 / ...

+2
source

Source: https://habr.com/ru/post/1258876/


All Articles