使用场景

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

原理解释

当你配置了 changeOrigin: true,所有请求先会请求的你本地的服务器,然后通过http-proxy-middleware代理到你配置的 target 服务器。

  1. module.exports = {
  2. devServer: {
  3. proxy: {
  4. '/api': {
  5. target: 'https://xx.dxy.net/',
  6. changeOrigin: true,
  7. ws: true,
  8. pathRewrite: {
  9. '^/api': ''
  10. }
  11. }
  12. }
  13. }
  14. }

本地请求的接口写法:

  1. axios.get('/api/admin/userInfo').then(res => {
  2. console.log(res)
  3. })

如果你本地起的服务为:http://localhost:8081,则接口请求的 request 会是:http://localhost:8081/admin/userInfo,但实际请求已经代理为https://xx.dxy.net/admin/userInfo,这样就就能在本地调试不同域名下的接口了。

关键解释

  • ‘/api’:类似正则作用,代理时会将 /api 替换为 target
  • changeOrigin:是否开启代理
  • pathRewrite:重写代理路径