首先,贴上nginx work的配置html
server{
listen 8099;
server_name wdm.test.cn;
location / {nginx
// 没有配置OPTIONS的话,浏览器若是是自动识别协议(http or https),那么浏览器的自动OPTIONS请求会返回不能跨域
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "$http_origin";
add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
add_header Access-Control-Max-Age "3600";
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
proxy_pass http://127.0.0.1:8080;
}
}ajax
其次,既然碰到了就想理解下为何须要这样,一开始脑壳还真钻进去了。跨域
如下引自知乎:浏览器
简单的说,你把Cookie托付给浏览器保存,浏览器要保证你的Cookie不被恶意网站利用。安全
同源策略并不能防止DDos,由于跨域的Ajax也会被请求,若是http://Evil.com用Ajax请求http://MyBank.com,浏览器会先发出 服务器
请求,而且带上http://MyBank.com的Cookie。拿到http://MyBank.com的响应以后(可能有敏感数据),浏览器才会根据Headercookie
里的Access-Control-Allow-Origin决定是否把结果交给http://Evil.com里的脚本。(或者先发一个OPTIONS请求看一下CORS设网站
置,再决定是否要发真正的请求。)spa
所以浏览器只是起到了最基本的防护,在写程序的时候仍是要注意防护CSRF,好比关键操做不要用GET,POST请求要作额外的验证(