记录一下VUE设置proxyTable本地代理实现跨域请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zqian1994/article/details/81369582

在简书上看到一个vue抓取qq音乐数据的demo,其内容数据都是通过调取qq音乐的接口获得,由于本地项目直接使用接口会抛错,因此需要通过代理来转发请求,在vue中通过修改vue proxyTable实现跨域请求接口数据。

具体配置方式如下:
在confid>index.js中修改proxyTable:{}为↓↓↓

proxyTable: {
      '/api': {
        target: 'https://c.y.qq.com',//需要代理的地址
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/' //这里理解成用‘/api’代替target里面的地址,调取接口时直接用/api代替
        }
      }
    },

注:在vue脚手架中配置完config,请重启一下项目,再进行接口的调用测试

项目统一的api.js中对接口调用方式如下,此处参考了element-admin中对接口进行请求时利用axios过滤器的写法;
具体可参考https://github.com/PanJiaChen/vueAdmin-template/blob/master/src/utils/request.js
或axios官方文档https://www.kancloud.cn/yunye/axios/234845
当然,请求接口也可直接在功能页面直接调用,此处不赘述

import request from '@/utils/request';// axios过滤器
//接口
export function getApi() {
  return request({
    url:'/api/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg',// 代理地址下的接口
    method:'get'
  })
}

页面中测试接口

created() {
      getApi().then((res) => {
        console.log(res);
      })
    },

猜你喜欢

转载自blog.csdn.net/zqian1994/article/details/81369582