vue-cli 3.x配置Proxy代理跨域

6,873 阅读1分钟

创建全局配置文件

如果你要在CLI3全局配置CLI,需要在根目录新建 vue.config.js 文件 官方文档

配置Proxy 代理

// vue.config.js
// 注意请求接口的时候不要加 baseURL 不然配置会失效
module.exports = {
  devServer: {
    proxy: {
        '/api': {
            target: 'http://localhost:9527',    // api接口基础路径
            changeOrigin: true,                 // 是否支持跨域
            ws: true,
            pathRewrite: {
              '^/api': ''                       // 重写路径:去掉路径中开头的 '/api'
            }
        }
    }
  }
}

注意! proxy 的匹配是从 target 开始匹配的。简单的来说,你需要把配置的baseURL去掉,不然会导致配置失败的情况。

例子:👇

// 这种情况配置是失败的。
axios.post('http://localhost:9527/api/admin/tests').then(res => {
  console.log('使用上面的proxy配置,会不成功的哦')
})

// 去掉 baseURL 后,配置就会成功
axios.post('/api/admin/tests').then(res => {
  console.log('我是成功的例子')
})

这里是配置成功的样子↓

代理成功的例子