1

Hi I have a problem with making a PUT request to an api with jquery.

This is my JavaScript:

var access_token = "##token##";
var service_url = "##url##";

var data = {
    access_token: access_token,
    id: this.getId(),
    content: this.getContent()
};
return $.ajax({
    method: 'PUT',
    url: service_url,
    data: data,
});

When I monitor the incoming calls on the Server this PUT Call will be received as an OPTIONS call.

OPTIONS /##url### HTTP/1.1.
Host: ##host##.
Connection: keep-alive.
Pragma: no-cache.
Cache-Control: no-cache.

GET and POST calls working in this way. If I do the same PUT call with Postman everything works without problems.

I tested some stuff like: contentType: 'text/json' headers: {"X-HTTP-Method-Override": "PUT"} parameters as a query parameters as JSON

Nothing works. Need some help. :)

The CORS headers are set on the Server. Access-Control-Allow-Origin → *

UPDATE I found the solution here: AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Chrome makes a preflight request(OPTIONS) before the real request to check for the cors headers. In my case this call was not handled correct.

I added some code to my NGINX on the server and then everything works.

if ($request_method = 'OPTIONS') {
  add_header 'Access-Control-Allow-Origin' '*';
  add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, OPTIONS';
  add_header 'Access-Control-Allow-Headers' 'Content-Type';
  add_header 'Content-Type' 'text/plain charset=UTF-8';
  add_header 'Content-Length' 0;
  return 204;
} 
Community
  • 1
  • 1
Schmidko
  • 690
  • 1
  • 7
  • 17
  • Possible duplicate of [AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?](http://stackoverflow.com/questions/21783079/ajax-in-chrome-sending-options-instead-of-get-post-put-delete) – Dave Apr 01 '17 at 19:13

2 Answers2

0

try this :

$.ajax({
method: 'PUT',
url: service_url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
});
aks7
  • 431
  • 3
  • 12
0

It's not method it's type

So,

$.ajax({
type: 'PUT',
url: service_url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8"
});
Rich S
  • 3,248
  • 3
  • 28
  • 49