关于vue本地与发布线上跨域问题解决

时间:2025-03-20 10:28:48

使用场景: 跳转


 = {
    publicPath: './',
    devServer: {
        proxy: {
          // 这里是配置代理的
        "/api": {
            target:'',
            changeOrigin: true,  // 允许跨域
            ws: true
          }
          
        }
      }
}

 

 = ({
  timeout: 30000,
  withCredentials: true
});

我们根据实际情况只需要修改proxyTable对于配置即可。假设我后端请求地址是,所有api的接口url都以/api开头。所以首先需要匹配所有以/api开头的.然后修改target的地址为。最后修改pathRewrite地址。将前缀 '^api' 转为 '/api'。如果本身的接口地址就有 '/api' 这种通用前缀,就可以把 pathRewrite 删掉。注意这个方式只能在开发环境中使用。

 location /api {
            proxy_pass http://127.0.0.1:9999;
            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' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Requested-With';
        }

因为在本地构建成功之后访问的是本地服务器转发远程服务器,如果发布到测试环境需要在nginx中配置对应的转发,即可解决跨域问题