vue访问外部接口

vue直接访问外部链接报错:ERR_FAILED

1、在vue.config.js中配置代理

module.exports = {
  devServer: {
    proxy: { //外部接口配置代理,解决跨域
      '/proxy/': {
        'target': 'https://www.test.com', //接口地址
        'secure': false, // false为http访问,true为https访问
        'changeOrigin': true, // 跨域访问设置,true代表跨域
        'pathRewrite': { // 路径改写规则
          '^/proxy': '' // 以/proxy/为开头的改写为''
        }
      }
    }
  }
}

2、然后使用axios调用接口,检测到'/proxy'会替代为https://www.test.com,这里实际访问到的接口就是https://www.test.com/api

axios.get('/proxy/api', { // 这里会匹配到前面我们设置的/proxy,代替为https://www.tianqiapi.com
    params: {
        version: 'v1',
        city: 'aa'
    }
}).then(function (response) {
    console.log(response)
}).catch(function (error) {
    console.log(error)
})

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值