配置vue.config.js处理前端跨域问题

配置vue.config.js处理前端跨域问题

这个地址在浏览器是可以直接打开访问
例子 完整路径 https://www.vue-js.com/api/v1/topics

在vue项目中使用

在这里插入图片描述

代码如下:

//点击按钮触发使用axios去掉接口
handleNew() {
        console.log('点击了跨域');
        axios({
              url: 'https://www.vue-js.com/api/v1/topics',
              method: 'get',
            }).then(res => {
              console.log('res',res)
            }); 
      },

结果报错如图:(发生了跨域)

在这里插入图片描述

解决:

// 在vue项目中找到vue.config.js文件 进行配置
// 完整路径  https://www.vue-js.com/api/v1/topics
// 以下我分了两种写法 '/api'的和 'topics'
  devServer: {
    proxy: {
      //方法一
      '/api': {//代理标识,一般是每个接口前的相同部分 就是在域名后面拼接的参数
        target: 'https://www.vue-js.com', // 这跨域的域名和端口号 不需要写路径
        changeOrigin: true, // 允许跨域请求
      },
      //方法二
      '/topics': { //代理标识可以随便写 topics topics1 top... 都行
		    target: 'https://www.vue-js.com', // 这跨域的域名和端口号 不需要写路径
		    changeOrigin: true,  // 允许跨域请求
		    pathRewrite:{  //用来做替换配置的 
		      '^/topics':'/api/v1/topics'  //可以替换成空或者其他路径
		    }
	   }
    },
  },

使用方法一点击跨域按钮

//使用axios访问'/api/v1/topics'路径识别'/api'标识并不替换所以就会用传进来的地址('/api/v1/topics')然后会代理成 target + '/api/v1/topics' ==>  https://www.vue-js.com/api/v1/topics
handleNew() {
        console.log('点击了跨域');
        axios({
              url: '/api/v1/topics',
              method: 'get',
            }).then(res => {
              console.log('res',res)
            }); 
      },

使用方法二点击跨域按钮

//使用axios访问'/topics'路径识别'/topics'标识先替换成'/api/v1/topics' 然后会代理成 target + pathRewrite ==>  https://www.vue-js.com/api/v1/topics
handleNew() {
        console.log('点击了跨域');
        axios({
              url: '/topics',
              method: 'get',
            }).then(res => {
              console.log('res',res)
            }); 
      },

因为是修改了vue.congig.js文件,最后重新运行一下项目 重新点击跨域按钮可以访问

在这里插接口正常入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值