Welcome to my website, have a nice day!
Dream it, Do it, Make it!

解决Vue前后端分离项目请求跨域问题

前后端分离的项目经常会出现跨域的问题,从VUE的角度,整理下目前我解决的两种方式。

一、前端项目通过npm启动

这时可以通过vue配置代理转发,主要修改有两点:

  • API接口配置

比如我的API地址是在.env.development这个文件里配置的:

# base api
# VUE_APP_API_BASE_URL = http://10.14.122.222:9099
VUE_APP_API_BASE_URL = http://localhost:3000    

将调用网关的API接口,改为VUE启动端口。

  • 配置代理

修改vue.config.js,代理部分修改为想要转发到的后台地址或网关:

  devServer: {
    proxy:{ 
        '/plat':{
            target:'http://localhost:9200/',
            ws:true,
            changeOrigin:true,
            pathRewrite:{
              '^/plat':''   
            }
        },
        '/mng':{
            target:'http://localhost:9202/',
            ws:true,
            changeOrigin:true,
            pathRewrite:{
              '^/mng':''   
            }
        }
    }
  }

这里我将比如http://localhost:3000/plat/users转发到http://localhost:9200/users的接口地址。

二、前端项目通过nginx启动

可以修改nginx的反向代理配置,如下:

 server {
        listen       7890;
        server_name  localhost;


        location /local-resource/ {
            proxy_pass   http://localhost:9200/resource;
            proxy_set_header    X-Forwarded-Host    $host;
            proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
            proxy_set_header    isLocal "IS_LOCAL";
        }

        location /plat/ {
            proxy_pass   http://localhost:9200/;
            proxy_set_header    X-Forwarded-Host    $host;
            proxy_set_header    X-Real-IP           $remote_addr;
            proxy_set_header    Host                $host;
            proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        }
    }

这样就将http://localhost:7890/local-resource?agent=SQM的地址代理到http://localhost:9200/resource?agent=SQM

赞(0)
未经允许禁止转载:Ddmit » 解决Vue前后端分离项目请求跨域问题

评论 抢沙发

登录

找回密码

注册