日志文章


2015-08-25

nginx options 跨域问题 请求HTTP错误405 用于访问该页的HTTP动作未被许可 Method Not Allowed

JavaScript JS 跨域问题

HTTP 错误 405 - 用于访问该页的 HTTP 动作未被许可

HTTP 错误 405.0 - Method Not Allowed

Nginx 处理跨域问题、OPTIONS 方法的问题

Method = "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | extension-method
extension-method = token

在Nginx location 里加上如下代码可以解决js 请求跨域问题:
注意,必须放在 location ... { ... }里面才能用if条件判断。

if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
return 200;
}


if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}


if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}


类别: 无分类 |  评论(1) |  浏览(8289) |  收藏
一共有 1 条评论
没楼可以吗 2015年08月25日10时50分 10:50 评论:
一开始在http { ... } 加了:

    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Headers X-Requested-With;
    add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

不行