跨域问题
原创...大约 2 分钟
跨域演示
出于浏览器的同源策略限制。同源策略是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说 Web 是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
当一个请求 URL 的协议、域名、端口三者之间任意一个与当前页面 url 不同即为跨域。
当前页面 url | 被请求页面 url | 是否跨域 | 原因 |
---|---|---|---|
http://www.test.com/ | http://www.test.com/index.html | 否 | 同源(协议、域名、端口号相同) |
http://www.test.com/ | https://www.test.com/index.html | 跨域 | 协议不同(http/https) |
http://www.test.com/ | http://www.baidu.com/ | 跨域 | 主域名不同(test/baidu) |
http://www.test.com/ | http://blog.test.com/ | 跨域 | 子域名不同(www/blog) |
http://www.test.com:8080/ | http://www.test.com:7001/ | 跨域 | 端口号不同(8080/7001) |
前端页面
<html>
<body>
<button onclick="test()">发送</button>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
function test() {
$.get("http://192.168.66.100:90/abc", function (result) {
alert(result);
});
}
</script>
</html>
如下报错
index.html:1 Access to XMLHttpRequest at 'http://192.168.66.100:90/abc' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
jquery.min.js:6 GET http://192.168.66.100:90/abc net::ERR_FAILED 200
核心错误字段:Access-Control-Allow-Origin
解决跨域
只需要在 Nginx 的配置文件中配置以下参数
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, 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';
if ($request_method = 'OPTIONS') {
return 204;
}
}
提示
Access-Control-Allow-Origin
表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求。
Access-Control-Allow-Methods
明确了客户端所要访问的资源允许使用的方法或方法列表。
Access-Control-Allow-Headers
设置预检请求。
Powered by Waline v2.15.7