最近在做vue.js项目,web服务器是Nginx,
要实现本地http://127.0.0.1跨域访问服务器端
https://bbc.wanxiaohong.cn,
并且要支持DELETE PUT等请求。
跨域配置
只需要在Nginx配置文件里加入以下配置,即可开启跨域
1 |
add_header Access-Control-Allow-Origin *; |
*代表任何域都可以访问,可以改成只允许某个域访问,如
Access-Control-Allow-Origin: https://bbc.wanxiaohong.cn。
这样的配置虽然开启了跨域请求,但只支持GET HEAD POST OPTIONS请求,使用DELETE发起跨域请求时,浏览器出于安全考虑会先发起OPTIONS请求,服务器端接收到的请求方式就变成了OPTIONS,所以引起了服务器的405 Method Not Allowed。
所以要对OPTIONS请求进行处理
详细配置:
1 2 3 4 5 6 7 |
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"; add_header Access-Control-Allow-Headers "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With"; #return 200; } |
当请求方式为OPTIONS时,设置Allow的响应头,重新处理这次请求。
配置好并重启Nginx,刷新页面重新发起请求,在控制台里你会发现,出现了二次请求,
第一次是OPTIONS请求,第二次才是DELETE请求,这就是对OPTIONS请求进行处理的结果,到这里总算完成了一次DELETE跨域请求了。
另附Apache跨域配置
1 2 3 4 5 6 |
<IfModule headers_module> header add Access-Control-Allow-Origin "请求此服务的地址" header add Access-Control-Allow-Credentials "true" header add Access-Control-Allow-Methods "GET, POST" header add Access-Control-Allow-Headers "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With" </IfModule> |