跳至主要內容

跨域问题

刘春龙原创...大约 2 分钟LinuxNginxWEB服务器教程文档

跨域演示

出于浏览器的同源策略限制。同源策略是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说 Web 是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

当一个请求 URL 的协议、域名、端口三者之间任意一个与当前页面 url 不同即为跨域。

当前页面 url被请求页面 url是否跨域原因
http://www.test.com/open in new windowhttp://www.test.com/index.htmlopen in new window同源(协议、域名、端口号相同)
http://www.test.com/open in new windowhttps://www.test.com/index.htmlopen in new window跨域协议不同(http/https)
http://www.test.com/open in new windowhttp://www.baidu.com/open in new window跨域主域名不同(test/baidu)
http://www.test.com/open in new windowhttp://blog.test.com/open in new window跨域子域名不同(www/blog)
http://www.test.com:8080/open in new windowhttp://www.test.com:7001/open in new window跨域端口号不同(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