Nginx解决转发地址时跨域的问题

2019-05-05 14:46:35 11166

一、什么是跨域问题


在一个服务器A里放置了json文件,另一个服务器B想向A发送ajax请求,获取此文件,会发生错误。


Chrome提示:


XMLHttpRequest cannot load ******. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

这就是跨域问题。解决方案有不少,比较好的是服务器端配置CORS,但要求服务器端做更改。如果在不需要更改服务器端的情况下解决呢?尤其是需要在本地测试的时候。


二、配置Nginx


打开nginx目录下的conf文件夹。打开nginx.conf,将其中的http请求修改为:


http {

  include mime.types;

  server {

    listen    80;

    server_name localhost;

    charset UTF-8;


  location / {

    root html;

    index index.html index.htm;

  }


    # Avoid CORS and reverse proxy settings

    location /api/ { # [2]

      proxy_http_version 1.1;

      proxy_pass http://www.landui.com/; # [3]


      add_header Access-Control-Allow-Origin *;

      add_header Access-Control-Allow-Methods "POST, GET, OPTIONS";

      add_header Access-Control-Allow-Headers "Origin, Authorization, Accept";

      add_header Access-Control-Allow-Credentials true;

    }

  }

}

注意粗体字的部分,/api/表示当请求api目录时,转向http://www.landui.com/域名。 

例如,请求:


http://www.landui.com/api/ 就会转向 http://www.landui.com/


http://www.landui.com/api/aaa/bbb/ 就会转向 http://www.landui.com/aaa/bbb/


这种由服务器转发的请求,可以突破跨域的限制,因此ajax也可以正常工作。


注意: /api/ 不行写成 /api。


http://www.landui.com/ 也不能写成 http://www.landui.com


三、配置hosts


为了在本机测试看起来更像在目标服务器上测试,可以设置系统的hosts文件。 

每个系统(windows、Linux、Mac OS)都有hosts文件,它是本地的域名解析器。 

通常,我们请求一个域名,如www.landui.com,首先要向域名服务器请求百度的IP地址,然后再根据IP地址来访问。


也可以不需要咨询域名服务器,直接在本地的hosts键入百度的IP地址。


例如 

252.192.0.15 www.landui.com


这样,系统会先从hosts文件里搜索IP地址。


Windows下的hosts文件位于:C:\Windows\System32\drivers\etc


打开后,添加


127.0.0.1 www.landui.com

则,每次访问www.landui.com,就会链接到本地。


提交成功!非常感谢您的反馈,我们会继续努力做到更好!

这条文档是否有帮助解决问题?

非常抱歉未能帮助到您。为了给您提供更好的服务,我们很需要您进一步的反馈信息:

在文档使用中是否遇到以下问题: