文章目录
1.什么是axios
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
axios官网:http://axios-js.com/zh-cn/docs/
GitHub原码: http://github.com/axios/axios
2.axios和ajax的关系
ajax技术实现了网页的局部数据刷新,axios实现了对ajax的封装。
3.特性
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF
4.安装
使用npm安装:npm install axios
使用 cdn: <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
5.执行get请求
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//ES6语法
axios.get("http://localhost:8080/user/getImage").then((res) => {
console.log(res.data.key);
_this.src = "data:image/png;base64,"+res.data.image;
_this.key = res.data.key;
});
6.执行post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//ES6语法
//发送axios
axios.post("http://localhost:8080/user/register?code=" + this.code+"&key="+this.key, this.user).then((res) => {
console.log(res);
if (res.data.state) {
alert(res.data.msg+"点击确定跳转到登录页面");
location.href='./login.html';
} else {
alert(res.data.msg);
}
});
7.执行多个并发请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
8.axios API(可以通过向 axios 传递相关配置来创建请求)
axios(config)
// 发送 POST 请求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
// 获取远端图片
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
更多请求配置可参考:http://axios-js.com/zh-cn/docs/#%E8%AF%B7%E6%B1%82%E9%85%8D%E7%BD%AE
9.创建实例(可以使用自定义配置新建一个 axios 实例)
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
10.拦截器(在请求或响应被 then 或 catch 处理前拦截它们)
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});