Nginx解决跨域问题(前端服务器,接口服务器)记录

Nginx解决跨域问题(前端服务器,接口服务器)记录

使用可视化工具宝塔,没有可忽略

遇到的问题:前端服务器访问接口服务器跨域

例:前端服务器访问地址 11.11.11.11:9008

​ 后端服务器访问地址 22.22.22.22:9009

通常是前端代码中访问接口http://22.22.22.22:9009/ceshi提示跨域

Access to XMLHttpRequest at ‘http://22.22.22.22:9009/ceshi’ from origin ‘http://11.11.11.11:9008’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

解决方式:

  1. 首先前端代码中访问自身地址,http://11.11.11.11:9008,不要去访问http://22.22.22.22:9009/ceshi

  2. 然后使用Nginx反向代理转发到http://22.22.22.22:9009

    修改11.11.11.11服务器上的Nginx配置指向接口地址

    proxy_pass http://22.22.22.22:9009;
    
listen 9008;
server_name www.xxx.com;
index index.php index.html index.htm default.php default.htm default.html;
root /www/wwwroot/www.xxx.com/xxx;

...
...
location /
    {
       proxy_pass http://22.22.22.22:9009;
       proxy_connect_timeout 60s;
       proxy_send_timeout 60s;
       proxy_read_timeout 60s;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header X-Forwarded-Proto http;

       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "upgrade";
       proxy_set_header Host $http_host;
    }

你可能感兴趣的:(demo记录,服务器,nginx,前端)