通过Vue解决跨域问题(proxy配置代理)

当我们在用本机去找服务器要数据时会产生跨域问题,所以利用vue-cli去开启一个代理服务器。

方法一:

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

//开启代理服务器(方式一)
   devServer: {
//请求服务器的地址
   proxy: 'http://localhost:5000'
  }

配置成功之后必须要重新启动脚手架,否则不会开启代理服务器

请求时:

axios.get("http://localhost:8081/students").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );

优点:配置简单,当请求资源时直接发给前端(8080)即可

缺点:不能配置多个代理,只能配置一个代理服务器,不能灵活的控制请求是否走代理。

工作方式:按照上述配置代理,当请求资源不存在时,请求会转发给服务器(优先匹配前端资源)

方法二:

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

//开启代理服务器(方法二)
    devServer: {
        proxy: {
            //  '/yu'为请求前缀,用于控制是不是走代理,想走代理时就在请求前缀前边加上这个请求前缀
            '/yu': {
                target: 'http://localhost:5000',
                pathRewrite: { "^/yu": "" }, //重写路径  匹配以/yu为开头的路径都变为空字符串 
                ws: true, //用于支持websocket
                changeOrigin: true //用于控制请求头中的host值
            },
            '/demo': {
                target: 'http://localhost:5001',
                pathRewrite: { "^/demo": "" },
                ws: true, //用于支持websocket
                changeOrigin: true //用于控制请求头中的host值
            },
        }
    }

请求时:

请求前缀必须跟着端口号

getStudents() {
      axios.get("http://localhost:8081/yu/students").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
    getCars() {
      axios.get("http://localhost:8081/demo/cars").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },

优点:可以配置多个代理,灵活的控制请求是否走代理

缺点:配置略繁琐,请求资源时必须加前缀

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值