美文网首页
Vue2.x-实现跨域请求(axios/proxytable)

Vue2.x-实现跨域请求(axios/proxytable)

作者: 叶叶叶xxx | 来源:发表于2019-04-15 00:03 被阅读0次

第一步:

首先找到vue-cli脚手架当中的config文件夹中的index.js



第二步:

在index.js当中找到



在proxyTable这个东西实现跨域请求


第三步:

修改代码

proxyTable: {
     '/img/': {
        // 图片api
        target: 'https://gank.io/api', // 接口域名
        changeOrigin: true, // 是否跨域
        secure: true, // 如果是https接口,需要配置这个参数为true`
        pathRewrite: {
          '^/img': '/' // 需要rewrite重写的
        }
      }
    }

接口域名中必须要有http或则https


第四步:

在命令行工具执行,修改了配置项需要重新跑一下程序

npm run dev

第五步:

使用axios的话可以先在main.js全局引入axios


import axios from 'axios'
Vue.prototype.$axios = axios

这样就可以直接使用this.$axios去请求了
还可以设置一下token和请求头

axios.defaults.headers.common['token'] = '' // 可以设置post,get或者common中的字段
axios.defaults.post['Content-type'] = 'application/json' // 请求头对应数据格式

第六步:

我们在组件当中使用axios请求一个图片的api
我使用的是 干货集中营的每日妹子图

created () {
    this.getData()
  },
methods: {
    getData () {
      this.$axios
        .get('/imgApi/pic/')
        .then(this.getDataSucc)
    },
    getDataSucc (res) {
      console.log(res)
    }
  }
打印出来的数据
Network

打印不出来的需关闭chrome的跨域限制
关闭chrome的跨域限制

相关文章

网友评论

      本文标题:Vue2.x-实现跨域请求(axios/proxytable)

      本文链接:https://www.haomeiwen.com/subject/dhkkwqtx.html