nginx反向代理解决跨域具体是怎样的?

vue打包后的静态资源部署到了nginx下的html文件夹里,start nginx后,在浏览器中输入localhost:9000/index.html看到了页面,但是数据请求的接口不是需要跨域就是代理到了localhost:9000,并没有代理到目标接口http://192.168.122.44:8000/R5Service


    server {
        listen       9000;
        server_name  localhost
        
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /api/ {
           proxy_pass http://192.168.122.44:8000/R5Service;
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

我在vue中用了两种请求,一种是

axios.defaults.baseURL = '/api/'

然后请求时如下

      this.axios.get("GetPilotJson").then(res => {
        console.log(JSON.parse(res.data));
      });

另一种是请求完整的接口地址

 this.axios.get("http://192.168.122.44:8000/R5Service/GetFlightJson").then(res => {
        console.log(JSON.parse(res.data));
      });

从下图看出
用api请求的从报错里可以看出请求的是http://localhost:9000/api/GetPilotJson,
直接请求的就会报跨域错误
图片描述

那么用nginx反向代理解决跨域到底是怎么操作的?

阅读 4.7k
4 个回答

你的问题在于proxy_pass的这个路由的问题

如果proxy_pass的URL定向里包括URI,那么请求中匹配到location中URI的部分会被proxy_pass后面URL中的URI替换,eg:
location /name/ {
    proxy_pass http://127.0.0.1/remote/;
}
请求http://example.com/name/test.html 会被代理到http://127.0.0.1/remote/test.html
如果proxy_pass的URL定向里不包括URI,那么请求中的URI会保持原样传送给后端server,eg:
location /name/ {
    proxy_pass http://127.0.0.1;
}

请求http://example/name/test.html 会被代理到http://127.0.0.1/name/test.html

如果你的Vue前端部署到了http://192.168.122.44这个服务...,然后在这个服务器上用nginx代理其他地址的接口,是解决跨域的一种方案。然而你现在前端在本地,nginx解决不了你的跨域问题

跨域的解决方案主要在后端接口程序上的配置,你甚至不需要nginx转发

建议封装axios为全局请求函数,里面定义通用的请求header,以及全局请求响应的拦截器,全局错误处理,以及全局捕获token失效重定向到登录页面

请求这个地址

/R5Service/GetFlightJson

这样试试看?

location /api/ {
   proxy_pass http://192.168.122.44:8000/R5Service/;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题