默认Access-Control-Allow-Origin开启跨域请求只支持GET、HEAD、POST、OPTIONS请求,使用DELETE发起跨域请求时,浏览器出于安全考虑会先发起OPTIONS请求,服务器端接收到的请求方式就变成了OPTIONS,所以引起了服务器的405 Method Not Allowed。
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, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,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; return204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin''*'; add_header 'Access-Control-Allow-Methods''GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers''DNT,X-CustomHeader,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-Methods''GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers''DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } }
示例二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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, POST, PUT, DELETE, PATCH, 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,Authorization,token'; return204; } 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, POST, PUT, DELETE, PATCH, 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,Authorization,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, POST, PUT, DELETE, PATCH, 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,Authorization,token'; }
其它技巧
Apache中启用CORS
在httpd配置或.htaccess文件中添加如下语句
1 2
SetEnvIf Origin "^(.*\.example\.com)$" ORIGIN_SUB_DOMAIN=$1 Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN