vue配置proxy跨域代理

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

以上配置结束
方式一:设置单个代理

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
//原路径http://192.168.1.182:3000/wgapi/vod/front/vodrank/getTagVideos

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, //是否使用link检查代码
  devServer: {
    // 设置代理服务器
    // 方法一:设置单个代理
    proxy: 'http://192.168.1.182:3000',
  }
});

方式二:设置多个代理

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  devServer:{
    proxy:{
      // 代理1
      //  当你请求是以/api开头的时候,则我帮你代理访问到http://127.0.0.1:3000
      '/api': {
        target: 'http://127.0.0.1:3000',
        // secure: false,// 如果是https接口,需要配置这个参数
        // ws: true, //是否代理websockets, 默认值为true
        
        /*
           changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:3000
           changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
           changeOrigin默认值为true
        */

        changeOrigin: true, // 设置请求头中的host地址,默认值为true
        //地址中的 /api 仅仅是一个请求转发标志,真正的接口中没有/api,所以在转发时重写请求路径,把/api删掉。
        pathRewrite: {'^/api' : ''}
      },
      // 代理2
      '/douyu':{
        target: 'http://open.douyucdn.cn',
         pathRewrite: {'^/douyu' : ''}
      }
    }

}

设置多个代理

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false, //是否使用link检查代码
  devServer: {
    //方式二:设置多个代理
    proxy:{
      //这个路径为http://192.168.1.182:3000/douyu/wgapi/vod/front/vodrank/getTagVideos
      '/douyu':{
        //target是代理的目标路径
        target:"http://192.168.1.182:3000",
        //pathRewrite重写请求的路径,实际请求的路径没有代理标识douyu,需要把斗鱼重置为空字符串
        pathRewrite:{'^/douyu':''}
      },
      //这个路径为http://192.168.1.182:3000/huya/wgapi/vod/front/vodrank/getTagVideos
      '/huya':{
        //target是代理的目标路径
        target:"http://192.168.1.182:3000",
        //pathRewrite重写请求的路径,实际请求的路径没有代理标识douyu,需要把斗鱼重置为空字符串
        pathRewrite:{'^/huya':''}
      }
    }
  }
});

发送ajax请求的方法使用

    getData() {
    //douyu代理
      axios.post('http://localhost:8080/douyu/wgapi/vod/front/vodrank/getTagVideos', { tagId: 0 }).then(res => {
        console.log('res.data:', res.data);
      });
		//huya代理
       axios.post('http://localhost:8080/huya/wgapi/vod/front/vodrank/getTagVideos', { tagId: 0 }).then(res => {
        console.log('res.data:', res.data);
      });
    },
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧寂173

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值