Vue2.5开发环境跨域配置(webpack,axios)

这里在开发环境中主要借助的是webpack里devServer下的proxy属性:
如果使用vue脚手架生成的webpack完整版,在build/webpack.dev.config.js中找到devServer;
如果是vue脚手架生成的webpack简版,在根目录的webpack.config.js文件中找到devServer;

添加如下内容:

devServer:{
  ...
  proxy:{
      '/api': {   //这里写的是想要跨域的请求的位置,一般写在当前项目封装的请求文件夹里
            rarget:'http://api.xxxx.com',   //webpack把您的当前的localhost也好其他地址也好,代理成和您指定的target同源
            changeOrigin: true,   //原文说:Set the option `changeOrigin` to `true` for name-based virtual hosted sites,类似把您的地址和要请求的地址一起托管,这样您就能跨域访问了
            pathRewrite:{
            '^/api':''   //这里必须写,就是您的url在请求里面写地址的时候需要前面加上/api/,这个加上以后会被转换为空,可以不必担心,但是一定要写
          }
      }
  }

这样webpack就配置完成了
怎么用呢?

axios.get('/api/xxx/xxx')  //这个接上面target+pathRewrite请求后面的内容

猜你喜欢

转载自blog.csdn.net/qq_29923881/article/details/81032590