Nginx 配置 Vue 项目解决跨域问题

例行交代背景 终于来了一个h5前端了。自己不用再去搞页面。因为前端是用 Vue 开发的,所以就会出现一个跨域的问题。

问题出现,我给的接口在自己调试的时候是正常访问正常返回数据,但是在他的项目调用接口报错:

Access to XMLHttpRequest at 'http://*******.com/23/sff' from origin 'http://***.**.**.**:**' 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.

这就涉及到跨域的问题。

这里我是用 Nginx 来部署 Vue 项目的,所以这里直接修改 Nginx 项目配置文件,先把配置附上

    server
    {
        listen 80;
        server_name test.com ;
        index index.html index.htm index.php;
        root  /home/dfs/h5/master;

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

        location / {
           try_files $uri $uri/ /index.html;
           if ($request_method = 'OPTIONS') {
                add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
                add_header Access-Control-Allow-Headers *;
                add_header Access-Control-Allow-Credentials 'true';
                return 200;
            }

            if ($request_method = 'POST') {
                add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Credentials 'true';
                add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
                add_header Access-Control-Allow-Headers *;
            }
        }

        location /api {
                proxy_pass http://baidu.com;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

        access_log  /home/wwwlogs/test.com.log;
    }

大概就是这样的配置。

location /api {
    proxy_pass http://baidu.com;  ## 服务端接口域名
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ## 包含了客户端和各级代理ip的完整ip链路
}

这个配置,主要是拦截相关的路由然后转发到对应服务端的接口去。

/api 这里是路由的一个路径,可以说类似一个标示。eg:

## 服务端给h5的接口地址
http://server.com/api/test

特别注意⚠️ :这里只需配置 H5 项目,不需要改动服务端的。举个栗子

## 服务端域名
http://server.com
## h5 域名
http://h5.com

## 接口地址
http://server.com/api/test

## 这个时候h5调用的接口则要使用自己的域名,然后通过 nginx 代理来实现转发,从而解决跨域的问题
http://h5.com/api/test
本作品采用《CC 协议》,转载必须注明作者和本文链接
好好管教自己,不要管别人
Zhengkx
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!