🚀
头像

默永


人生就像骑单车,想保持平衡就得往前走。

vue - 脚手架配置代理

2023-02-03 17:41:59 269 💗 0 @默永

在main.js文件中引入axios,然后Vue.prototype.$http = axios,就可以使用this.$http.get();调用

方法一

vue.config.js添加如下配置:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, //忽略lint检测
  devServer: {
    proxy: 'http://localhost:200'
  }
})
  1. 优点:配置简单,请求资源直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制求情是否走代理。
  3. 工作方式:若按照上述配置代理,当请求前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)

方法二

编写vue.config.js配置具体代理规则

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, //忽略lint检测
  devServer: {
    proxy: {
      '/api1': { // 匹配所有已 '/api1' 开头的请求路径
        target: 'http://localhost:5000', // 代理目标的基础路径
        ws: true, // 用于支持websocket
        pathRewrite: { '^/api1': '' },  // 使用正则表达式过滤掉请求前缀
        changeOrigin: true
      },
      '/api2': { // 匹配所有已 '/api2' 开头的请求路径
        target: 'http://localhost:5001', // 代理目标的基础路径
        ws: true, // 用于支持websocket
        pathRewrite: { '^/api2': '' },  // 使用正则表达式过滤掉请求前缀
        changeOrigin: true
      }
    }
  }
})
/*
  changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
  changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
  changeOrigin默认值为true
*/
  1. 优点:可以匹配多个代理。且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。
    目录导航