首页 > 技术文章 > vue脚手架配置代理

birdy-silhouette 2021-08-18 14:13 原文

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

module.exports = {
	devServer: {
      proxy: {
      '/api1': {	// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',	// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api1': ''}		//访问时替换带有/api1的路径部分
      },
      '/student': {
        target: 'http://localhost:5001',
        changeOrigin: true,
        pathRewrite: {'^/student': ''}	
          /*
          访问http://localhost:8080/student/getInfo时真实访问的地址是						  				http://localhost:5001/getInfo
          */       	
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

推荐阅读