- axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
get请求
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
post请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
拦截器
// 请求拦截器 axios.interceptors.request.use((config)=> { btn.innerHTML='请求数据中'; return config; }, // 错误时发生的事情 (err)=>{ console.log(err) }); // 响应应拦截器 axios.interceptors.response.use((config)=> { btn.innerHTML='请求数据成功'; return config; }, // 错误时发生的事情 (err)=>{ console.log(err) });