Nginx CORS 跨域 出现 405 Not Allowed 的解决方案

首先,这里解决的不是忘了设置 Access-Control-Allow-* 头的问题,那个只有记得输出就可以了。

问题描述,执行如下jQuery代码:

var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://192.168.1.1/test_path/?m=test/cors",
    "method": "POST",
    "headers": {
        "content-type": "application/json"
    },
    "processData": false,
    "data": "{"OK":123}"
}

$.ajax(settings).done(function (response) {
    console.log(response);
});

服务器返回如下HTTP头:

HTTP/1.1 405 Not Allowed
Server: nginx
Date: Tue, 01 Aug 2017 15:20:43 GMT
Content-Type: text/html
Content-Length: 570
Connection: keep-alive

问题在哪里,如果我们单独创建一个文件又是正常的,有时候甚至开始怀疑底层的PHP代码是否干了什么事情,但是这里的逻辑单独创建一个文件又一点问题都没有。注意了,单独创建一个文件。

然后我把地址该了一下,改为http://192.168.1.1/test_path/index.php?m=test/cors,紧接着,奇迹发生了。

服务器返回了如下类容:

HTTP/1.1 204 No Content
Server: nginx
Date: Tue, 01 Aug 2017 15:26:06 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Access-Control-Allow-Origin: http://localhost:4005
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-requested-with,content-type,cache-control
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS

到此,问题找到,怎么解决就不说了,发现问题,找到原因就好,解决的方案有很多,不废话。这里只是记一种现象,针对nginx的目录配置,很有可能是不支持OPTIONS请求的。

一条评论在“Nginx CORS 跨域 出现 405 Not Allowed 的解决方案”

写下你最简单的想法