第一步:
首先找到vue-cli脚手架当中的config文件夹中的index.js
![](https://img.haomeiwen.com/i17047038/b9e03e933667414a.png)
第二步:
在index.js当中找到
![](https://img.haomeiwen.com/i17047038/9d291273b88a35ad.png)
在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
![](https://img.haomeiwen.com/i17047038/9fa3ed1b34e9909f.png)
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)
}
}
![](https://img.haomeiwen.com/i17047038/1c4642a59f5854e5.png)
![](https://img.haomeiwen.com/i17047038/bc62e349629cacc5.png)
打印不出来的需关闭chrome的跨域限制
关闭chrome的跨域限制
网友评论