【问题标题】:Requesting an API with jQuery .ajax() PUT is not working使用 jQuery .ajax() PUT 请求 API 不起作用
【发布时间】:2017-08-25 13:10:37
【问题描述】:

您好,我在使用 jquery 向 api 发出 PUT 请求时遇到问题。

这是我的 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,
});

当我监控服务器上的传入呼叫时,此 PUT 呼叫将作为 OPTIONS 呼叫接收。

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

GET 和 POST 调用以这种方式工作。 如果我使用 Postman 进行相同的 PUT 调用,一切正常。

我测试了一些东西,例如: 内容类型:'文本/json' 标头:{“X-HTTP-Method-Override”:“PUT”} 参数作为查询 JSON 格式的参数

没有任何作用。需要一些帮助。 :)

CORS 标头在服务器上设置。 访问控制允许来源 → *

更新 我在这里找到了解决方案: AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Chrome 在真正请求检查 cors 标头之前发出预检请求(OPTIONS)。在我的情况下,这个调用没有被正确处理。

我在服务器上的 NGINX 中添加了一些代码,然后一切正常。

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;
} 

【问题讨论】:

标签: jquery ajax cors put


【解决方案1】:

试试这个:

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

【讨论】:

  • 同样的错误。从服务器收到的请求是 OPTIONS 调用。
【解决方案2】:

不是method,是type

所以,

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

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2018-05-20
    相关资源
    最近更新 更多