vue3解决CORS 错误

3,838 阅读1分钟

第一步

创建vue.config.js文件

  //创建vue.config.js文件
  module.exports = {
  lintOnSave: false,//是否在保存时检查
  devServer: {
    host: 'localhost',//本机ip
    port: 3000,//本机端口
    open: true,
    proxy: {
      '/api': {  //代理别名
        target: 'http://api.baidu.com/',   //代理目标服务器地址
        changeOrigin: true,
        secure: true,
        pathRewrite:{  //替换路径中的/api
          '^/api':''
        }
        /*pathRequiresRewrite: {
          '^/api': ''
        }*/
      }
    },
    overlay: {
      warning: false,
      errors: true
    }
  }
}

第二步

//修改axios的默认根路径
axios.defaults.baseURL = '/api';

 

在vue中使用proxy解决跨域问题

在vue中使用proxy进行跨域的原理是:将域名发送给本地的服务器(启动vue项目的服务,loclahost:8080),再由本地的服务器去请求真正的服务器。

1.在proxy中设置要访问的地址,并重写/api为空的字符串,因为我们真正请求的地址是没有带/api,这个重写很重要!!!

2.在创建axios实例的时候将baseURL设置为/api ,这时候我们的跨域就已经完成了。

3. 假如请求的真正地址为:http://121.121.67.254:8185/core/getdata/userInfo,但我们在浏览器上会看到是这样的: http://localhost:8080/api/core/getData/userInfo ,多了个/api,但并不影响我们请求数据。

vue.config.js

module.exports = {
    // baseUrl: process.env.NODE_ENV === 'production' ? '/' : '/',
    assetsDir: 'static',
    productionSourceMap: false,
    devServer: {
        host:'127.0.0.1',
        // host:'192.168.0.89',
        port:'8080',
        proxy: {
            '/api':{
                target:'http://192.168.0.182',//这里后台地址;填写真实的后台接口
                ws: true,
                changeOrigin:true,//允许跨域
                pathRewrite:{
                    '^/api':''
                }
            }
        }, // 设置代理
        headers: {
          'Access-Control-Allow-Origin': '*',
        },
        before: app => {}
    },
    // 第三方插件配置
    pluginOptions: {
        //...
    },
    lintOnSave: false
}