vue中如何配置代理解决浏览器跨域问题
vue中如何配置代理解决浏览器跨域问题
方法一:在vue.config.js中添加如下配置
//开启代理服务器(方式一)
   devServer: {
//请求服务器的地址
   proxy: 'http://localhost:5000'
  }
配置成功之后必须要重新启动脚手架,否则不会开启代理服务器
请求时:
axios.get("http://localhost:8080/students").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
优点:配置简单,当请求资源时直接发给前端(8080)即可
缺点:不能配置多个代理,只能配置一个代理服务器,不能灵活的控制请求是否走代理。
工作方式:按照上述配置代理,当请求资源不存在时,请求会转发给服务器(优先匹配前端资源)
方法二:在vue.config.js中添加如下配置
//开启代理服务器(方法二)
    devServer: {
        proxy: {
            //  '/api1'为请求前缀,用于控制是不是走代理,想走代理时就在请求前缀前边加上这个请求前缀
            '/api1': {
                target: 'http://localhost:5000', // 目标请求的地址端口号是5000
                pathRewrite: { "^/api1": "" }, //重写路径  匹配以/api1为开头的路径都变为空字符串 (确保url路径是正确的)
                ws: true, //用于支持websocket
                changeOrigin: true //用于控制请求头中的host值
            },
            '/api2': {
                target: 'http://localhost:5001',
                pathRewrite: { "^/api2": "" },
                ws: true, //用于支持websocket
                changeOrigin: true //用于控制请求头中的host值
            },
        }
    }
请求时:请求前缀必须跟着端口号
getStudents() {
      axios.get("http://localhost:8080/api1/students").then(   //此时匹配api1这个代理
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
    getCars() {
      axios.get("http://localhost:8080/api2/cars").then(   //此时匹配api2这个代理
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
优点:可以配置多个代理,灵活的控制请求是否走代理
缺点:配置略繁琐,请求资源时必须加前缀
 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号