Vue 跨域配置(生产环境、开发环境)

1,111 阅读1分钟

最近在和其他公司联调API,但是他们那边又不给开启跨域,那只能自己解决了。

生产环境

  1. axios关键配置

    import axios from 'axios';
    
    axios.defaults.timeout = 10000;
    axios.defaults.baseURL = 'api/';
    
    // http request 拦截器
    axios.interceptors.request.use(
      (config) => {
        // ...
        return config;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
    
    // http response 拦截器
    axios.interceptors.response.use(
      (response) => {
        return response.data;
      },
      (err) => {
        return Promise.reject(err);
      }
    );
    
    export default axios;
    
  2. devServer 配置

    1. 新建 vue.config.js
    2. 添加如下内容
    module.exports = {
      devServer: {
        https: true,
        proxy: {
          '/api': {
            target: 'http://xxx.com/ds-dc-rest/',
            secure: false,
            changeOrigin: true,
            pathRewrite: { '^/api': '/' }
          }
        }
      }
    };
    

开发环境

打包发布到线上以后会发现所有接口都出现了跨域限制,所以开发环境需要进行单独设置。 如果使用的是的是宝塔,只需要进行如下配置即可:

  1. 打开网站设置 打开网站设置
  2. 修改配置文件,增加如下内容: 修改配置文件
    // 所有 /api 开头的都转发到目标服务器
    location /api {
        proxy_pass http://xxx.com/ds-dc-rest/;
    }
    
    // 如果 Vue Router 设置了 history 模式
    // 需要增加如下内容,不然刷新会出现 404
    location / {
        try_files $uri $uri/ /index.html;
    }