0

Basically, when I make a PUT request using jQuery.ajax method. It does not work properly.

For example:

$.ajax({
    "url": "http://quironapi.twotigers.local/cidades/editar/1",
    "method": "PUT",
    "type": "json",
    "data": JSON.stringify({
        "latitude": 2
    }),
    contentType: "application/json; charset=utf-8"
}).done(function(resultado){
    console.log("dados atualizados", resultado);
}).fail(function(err){
    console.log("falha ao atualizar", err);
});

will show me this on console: enter image description here

But, when I make the same request with ARC (a postman like chrome extension), it shows me that the Access-Control-Allow-Origin is present already:

enter image description here

Also, the "insert/create" request using POST method instead of PUT works fine. I tried to use fetch api as well but it returns me the same cors origin error.

What am I missing?

CarlosCarucce
  • 2,874
  • 1
  • 25
  • 43

1 Answers1

2

From MDN Web Docs ;

HTTP methods other than GET, or POST with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request.

Since you are sending a PUT request, you must deal with OPTIONS method first and then after the approval, you'll be able to send your PUT request. So you need to explicitly indicate the methods you allow in the back-end, for example if you're in control of the API and let's say it uses Express, you could use the below approach.

res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
Efkan G
  • 103
  • 1
  • 7