|
默认Access-Control-Allow-Origin开启跨域请求只支持GET、HEAD、POST、OPTIONS请求,使用DELETE发起跨域请求时,浏览器出于安全考虑会先发起OPTIONS请求,服务器端接收到的请求方式就变成了OPTIONS,所以引起了服务器的405 Method Not Allowed.
解决方法
首先要对OPTIONS请求进行处理
if ($request_method = 'OPTIONS') {
? ?add_header Access-Control-Allow-Origin *;
? ?add_header Access-Control-Allow-Methods GET,OPTIONS;
? ?#其他头部信息配置,省略...
? ?return 204;
}
当请求方式为OPTIONS时设置Allow的响应头,重新处理这次请求.这样发出请求时第一次是OPTIONS请求,第二次才是DELETE请求.
# 完整配置参考
# 将配置文件的放到对应的server {}里
add_header Access-Control-Allow-Origin *;
location / {
? ?if ($request_method = 'OPTIONS') {
? ? ? ?add_header Access-Control-Allow-Origin *;
? ? ? ?add_header Access-Control-Allow-Methods GET,OPTIONS;
? ? ? ?return 204;
? ?}
? ?index index.php;
? ?try_files $uri @rewriteapp;
}
实例四:更多配置示例
The following Nginx configuration enables CORS,with support for preflight requests.
#
# Wide-open CORS config for nginx
#
location / {
? ? if ($request_method = 'OPTIONS') {
? ? ? ?add_header 'Access-Control-Allow-Origin' '*';
? ? ? ?add_header 'Access-Control-Allow-Methods' 'GET,OPTIONS';
? ? ? ?#
? ? ? ?# Custom headers and headers various browsers *should* be OK with but aren't
? ? ? ?#
? ? ? ?add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,X-Requested-With,Content-Type';
? ? ? ?#
? ? ? ?# Tell client that this pre-flight info is valid for 20 days
? ? ? ?#
? ? ? ?add_header 'Access-Control-Max-Age' 1728000;
? ? ? ?add_header 'Content-Type' 'text/plain charset=UTF-8';
? ? ? ?add_header 'Content-Length' 0;
? ? ? ?return 204;
? ? }
? ? if ($request_method = 'POST') {
? ? ? ?add_header 'Access-Control-Allow-Origin' '*';
? ? ? ?add_header 'Access-Control-Allow-Methods' 'GET,OPTIONS';
? ? ? ?add_header 'Access-Control-Allow-Headers' 'DNT,Content-Type';
? ? }
? ? if ($request_method = 'GET') {
? ? ? ?add_header 'Access-Control-Allow-Origin' '*';
? ? ? ?add_header 'Access-Control-Allow-Methods' 'GET,Content-Type';
? ? }
}
if ($request_method = 'OPTIONS') { ?
? ?add_header 'Access-Control-Allow-Origin' 'https://docs.domain.com'; ?
? ?add_header 'Access-Control-Allow-Credentials' 'true'; ?
? ?add_header 'Access-Control-Allow-Methods' 'GET,PATCH,OPTIONS'; ?
? ?add_header 'Access-Control-Allow-Headers' 'DNT,token'; ?
? ?return 204;
}
if ($request_method = 'POST') { ?
? ?add_header 'Access-Control-Allow-Origin' 'https://docs.domain.com'; ?
? ?add_header 'Access-Control-Allow-Credentials' 'true'; ?
? ?add_header 'Access-Control-Allow-Methods' 'GET,token'; ?
} ?
if ($request_method = 'GET') { ?
? ?add_header 'Access-Control-Allow-Origin' 'https://docs.domain.com'; ?
? ?add_header 'Access-Control-Allow-Credentials' 'true'; ?
? ?add_header 'Access-Control-Allow-Methods' 'GET,token'; ?
}
其它技巧
Apache中启用CORS (编辑:网站开发网_马鞍山站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|