一、axios介绍
Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。
Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。
Github开源地址: GitHub - axios/axios: Promise based HTTP client for the browser and node.js
二、axios使用
1.get方法(我们可以简单的读取 JSON 数据)
// 引入axios
import axios from 'axios';
//我们可以简单的读取 JSON 数据:
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://www.baidu,com')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
// 直接在 URL 上添加参数 ID=12345
axios.get('/book?id=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 也可以通过 params 设置参数:
axios.get('/book', {
params: {
id: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2. post方法
//创建实例
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.post('https://www.runoob.com/try/ajax/demo_axios_post.php')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
console.log(error);
});
}
})
//POST 方法传递参数格式如下
axios.post('/book', {
firstName: '三国演义' // 参数 firstName
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.拦截器
在请求或响应被 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);
});