【发布时间】:2016-02-24 02:16:26
【问题描述】:
我在服务器端使用 PHP,在前端使用 Backbone.js。我可以执行 GET 和 POST 请求,但似乎无法让 PUT 或 DELETE 工作。
我不能 100% 确定放置标题的最佳位置在哪里。我在两个地方都有。 .htaccess文件中的一个如下。
#Header always set Access-Control-Allow-Origin "http://www.fitnesstimer.dev"
#Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
#Header always set Access-Control-Allow-Headers "origin, x-requested-with, Content-Type,X-Custom-Header"
#header always set Access-Control-Allow-Credentials "true"
然后在我的控制器的标题中我有这个。
header('Access-Control-Allow-Origin: http://www.fitnesstimer.dev');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, X-Custom-Header');
header('Access-Control-Allow-Credentials: true');
我的 AJAX 调用如下所示。
$.ajax({
type: 'PUT',
url: 'http://www.fitnesstimerapi.dev/user/deleteuser/' + userId,
contentType: "application/json",
xhrFields: {withCredentials: true },
dataType: "text",
success: function() {
alert( 'User removed!' );
},
error: function( err ) {
console.log( "ERROR: ", err );
}
});
我已经尝试过 PUT 和 DELETE 作为类型,但都不起作用。我收到以下错误。
XMLHttpRequest cannot load http://www.fitnesstimerapi.dev/user/deleteuser/11. Response for preflight has invalid HTTP status code 404
【问题讨论】:
-
错误中提到“preflight”意味着浏览器正在发送“OPTIONS”命令并且没有从您的服务器获得它期望的答案。作为 CORS 支持的一部分,您的 PHP 是否正确实现了“OPTIONS”请求?
-
我确信它没有,我也不知道该怎么做。
-
哦,伙计,您只是说“您的 PHP 是否正确实现了“选项”请求作为您的 CORS 支持的一部分?”我能够基于此进行搜索,并找到了此链接。 dinochiesa.net/?p=754
标签: javascript php ajax cors