功能特性
-
从浏览器中创建 XMLHttpRequests
-
从 node.js 创建 http 请求
-
支持 Promise API
-
拦截请求和响应
-
转换请求数据和响应数据
-
取消请求
-
自动转换 JSON 数据
-
客户端支持防御 XSRF
安装 并在src/main.js配置 axios
npm install axios --save-dev 安装
import axios from 'axios' 引入 axios
Vue.prototype.$axios= axios 将axios绑定给vue成为一个属性
常用方法例子
Get 方法 params传递参数
this.$axios.get(url, {
params: {
// get方法params传递参数
a: '1'
}
})
.then(response => {
//成功返回
console.log(response);
})
.catch(error => {
//失败返回
console.log(error);
});
Post 方法 传参数据必须放在消息主体中
this.$axios.post(url, {a: '1'})
.then(response => {
//成功返回
console.log(response);
})
.catch(error => {
//失败返回
console.log(error);
});
axios底层方法
this.$axios({
method: "get", //请求方法 [get/post]
url: 'https://api.apiopen.top/getImages', // 请求地址
params: {
a: '1' // 请求参数
}
})
.then(response => {
//成功返回
console.log(response);
})
.catch(error => {
//失败返回
console.log(error);
});
跨域请求代理
1、打开config/index.js 找到
module.exports{
dev: {
proxyTable{},
}
}
2 proxyTable{},改成
/*配置跨域*/
proxyTable: {
'/api': {
target: 'https://api.apiopen.top/getJoke', //设置你调用的接口域名和端口号 别忘了加http
changeOrigin: true, //如果接口跨域,需要进行这个参数配置
secure: false, // 如果是https接口,需要配置这个参数
pathRewrite: {
'^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们调用接口时直接用api代替
}
}
}
网友评论