webpack+axios项目中跨域问题的解决

在项目config/index.js文件中,增加proxyTable配置,使用代理方式实现跨域请求,修改如下:

dev: {
      env: require('./dev.env'),
      port: 8080,
      autoOpenBrowser: true,
      assetsSubDirectory: 'static',
      assetsPublicPath: '/',
      proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
      cssSourceMap: false,


      proxyTable: { // 在这里配置如下代码
   '/api': {
                target:'http://192.168.1.108:8081', // 你请求的第三方接口
                changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
                pathRewrite:{  // 路径重写,
          '^/api': '/'  
            }
        } 
    }
  }

在代码中调用如下:

axios.get(`/api/user/getUser.do`, { params: params });     

看起来访问的地址是:http://localhost:8080/api/user/getUser.do
实际访问地址则为:http://192.168.1.108:8081/user/getUser.do

猜你喜欢

转载自my.oschina.net/u/1011854/blog/1630133