有很多时候你在构建应用时需要访问一个 API 并展示其数据。做这件事的方法有好几种,而使用基于 promise 的 HTTP 客户端 axios 则是其中非常流行的一种。
https://www.cnblogs.com/nogodie/p/9853660.html
https://www.jianshu.com/p/4ee31fdb78b6
安装:
npm install axios --save
导入:
在main.js导入:
// 引入axios,并加到原型链中
import axios from 'axios';
Vue.prototype.$axios = axios;
import QS from 'qs'
Vue.prototype.qs = QS;
axios.defaults.baseURL = '/api'
解决跨域:
https://my.oschina.net/u/3234821/blog/3046256
https://blog.csdn.net/github_33809414/article/details/81774885
https://blog.csdn.net/James_liPeng/article/details/86151073
https://blog.csdn.net/wh_xmy/article/details/87705840
config/index.js 文件下proxyTable中配置地址
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': { //代理地址
target: 'http://192.168.0.155:8010', //需要代理的地址, 实际生产环境需要访问的地址
changeOrigin: true, //是否跨域
secure: false,
pathRewrite: {
'^/api': '/' //本身的接口地址没有 '/api' 这种通用前缀,所以要rewrite,如果本身有则去掉
}
}
},
使用:
this.$axios({
method:'post',
url:'/res/imgUpload'
}).then(res=>{
console.log(res)
}).catch(error=> {
console.log(error)
})