Vue-cli配置代理

在前后端直接配置一个代理服务器,这个代理服务器和前端处于一个位置,当前端向后端请求数据的时候,不会直接访问后端,而是找这台代理,代理收到前端的请求,转发给后端,如果收到后端的响应数据,就把这些数据返回给前端。

方法一

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

devServer: {
    proxy: 'http://localhost:5000'
}

请求方法

getStudents() {
//get 8080/students,配置后将请求转给5000端口     
axios.get('http://localhost:8080/students').then(
        response => {
          console.log('请求成功了!', response.data);
        },
        err => {
          console.log('请求失败', err.message);
        }
      )
    },

说明

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活控制请求是否走代理,如果前端工作目录下有请求的路径(重名),则会默认不走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时。那么该请求会转发给服务器(优先匹配前端资源)。

方法二

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

 devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        // 重写路径,如果不写这个,请求时路径会把/api也带过去
        pathRewrite: {'^/api':''},
        ws: true,//用于支持websocket
        //告诉请求的服务器,请求来自于哪里,ture则撒谎告诉他来自自身服务器5000,fasle则实话实说,来自于8080
        changeOrigin: true//用于控制请求头中的host值
      },
      '/demo': {
        target: 'http://localhost:5001',
        pathRewrite: {'^/demo':''},
      }
    }
  }
  • changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
  • changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
  • changeOrigin默认为true。
    请求方法
getStudents() {
      axios.get('http://localhost:8080/api/students').then(
        response => {
          console.log('请求成功了!', response.data);
        },
        err => {
          console.log('请求失败', err.message);
        }
      )
    },
getCars() {
      axios.get('http://localhost:8080/demo/cars').then(
        response => {
          console.log('请求成功了!', response.data);
        },
        err => {
          console.log('请求失败', err.message);
        }
      )
    }
  }

说明

  1. 优点:可以配置多个代理,且可以灵活的控制请求是都走代理,不走代理则不加配置的代理名,例如http://localhost8080/api/students就是走代理,http://localhost8080/students就是不走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀,指我们配置的代理名,这里是/api