webpack的代理proxy配置

2,057 阅读1分钟

情形一:配置代理如下

vue-cli3.0以前版本配置/config/index.js文件:

module.exports = {
  dev: {
    proxyTable: {
      '/api/**': {
        target: 'http://10.10.17.64:8082/',
        changeOrigin: false,
        secure: false,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

vue-cli3.0以后的版本配置vue.config.js文件:

module.exports = {
  devServer: {
    proxy: {
      '/api/**': {
        target: 'http://10.10.17.64:8082/',
        changeOrigin: false,
        secure: false,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

刷新页面报错

SyntaxError: Invalid regular expression: //api/**/: Nothing to repeat

好像是说/api/**这个匹配有问题。

官方文档说明

于是查阅webpack官方文档:

www.webpackjs.com/configurati…

说明如下:

请求到 /api/users 现在会被代理到请求 http://localhost:3000/api/users。

如果你不想始终传递 /api ,则需要重写路径:

proxy: {
  "/api": {
    target: "http://localhost:3000",
    pathRewrite: {"^/api" : ""}
  }
}

正确配置如下

所以去掉/**以为是通配的通配符就好了……

proxy: {
  '/api': {
    target: 'http://10.10.17.64:8082/',
    changeOrigin: false,
    secure: false,
    pathRewrite: {
      '^/api': ''
    }
  }
}

情形二:配置代理如下

'/birt': {
  target: 'http://10.10.17.99:6013/',
  changeOrigin: false,
  secure: false,
  pathRewrite: {
    '^/birt': ''
  }
},

刷新页面报错

当存在路由birtCustoms时,会和接口调用冲突。

正确配置如下

'/birt/': { // 配置的时候最好加上竖杠,为了防止birt开头的路由当做接口去调用了。
  target: 'http://10.10.17.99:6013/',
  changeOrigin: false,
  secure: false,
  pathRewrite: {
    '^/birt/': ''
  }
},

延伸配置问题

最好所有的接口调用前缀全用/api/开头,这样便于区分是接口调用还是路由跳转。

否则使用IIS服务器部署前端时容易出问题,详见另一篇文章记录。

juejin.cn/user/281954…