关于跨域问题的思考和解决思路
前言
什么是跨域?
当两个域具有相同的协议(如http), 相同的端口(如80),相同的host(如www.google.com),那么我们就可以认为它们是相同的域(协议,域名,端口都必须相同)。
跨域就指协议、域名、端口不一致,出于安全考虑,跨域的资源之间是无法交互的。
请求的目标URL和所在网页的URL的协议、域名、端口有一个不同,就算是跨域了。
因此向服务器发送请求会返回No 'Access-Control-Allow-Origin' header is present on the requested resource
的错误。
如下图,我想使用jQuery中的get方法访问自己服务器上的文件
结果返回如下bug
方式1 - 修改后端配置
nginx配置文件nginx.conf
中加上这几句
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified- Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
以上,重新启动nginx,再向服务器发送请求,即可成功获取响应数据
方式2 - 前端使用jsonp请求
- 描述:No ‘Access-Content-Allow-Origin’ header is present on the requested requested resource
- https://github.com/RekingZhang/axios-jsonp
- https://github.com/RekingZhang/axios-jsonp/tree/master/dist
后记
推荐阅读 - 跨域踩坑经验总结(内涵:跨域知识科普)