使用 ajax API 发送 PUT 请求时出现 Cors 错误

Cors error when sending a PUT request with ajax API

基本上,当我使用 jQuery.ajax 方法发出 PUT 请求时。它不能正常工作。

例如:

$.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);
});

将在控制台上显示:

但是,当我使用 ARC(像 chrome 扩展名这样的邮递员)发出相同的请求时,它显示 Access-Control-Allow-Origin 已经存在:

此外,使用 POST 方法而不是 PUT 的“insert/create”请求工作正常。 我也尝试使用 fetch api 但它 returns 我遇到了相同的 cors 来源错误。

我错过了什么?

来自 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.

由于是发送PUT请求,必须先处理OPTIONS方法,审核通过后,才能发送PUT请求。所以你需要在 back-end 中明确指出你允许的方法,例如,如果你控制 API 并且假设它使用 Express,你可以使用下面的方法。

res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');