什么是axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。中文官网地址
特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
安装
npm:
npm install axios
yarn:yarn add axios
cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
创建实例 axios.create(config)
// 创建axios实例
const http = axios.create({
baseURL: baseUrl, // baseUrl
timeout: 5000 // 超时时间
// 更多配置项可以看看官网这里不过多赘述
})
拦截器
在请求或响应被
then或catch处理前拦截它们,然后对它们做一些不可描述的事情。
请求拦截器
// 添加请求拦截器
axios.interceptors.request.use(function(config) {
// 在发送请求之前做些什么
config.headers = {
'content-type': 'application/json',
'token': getToken()
}
return config;
}, function (error) {
// 请求错误
return Promise.reject(error);
});
响应拦截器
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对返回数据做点啥 比如状态进行拦截
if (response.data.status !== 200) {
Toast({
message: response.data.message,
type: 'warning',
duration: 1000
})
return
}
// 没问题 返回服务器数据
return response.data;
}, function (error) {
// 响应错误
return Promise.reject(error);
});
实例添加拦截器
// 实例同样可以添加拦截器
const http = axios.create({
baseURL: baseUrl, // baseUrl
timeout: 5000 // 超时时间
// 更多配置项可以看看官网这里不过多赘述
})
http.interceptors.request.use(function () {...})
http.interceptors.response.use(function () {...})
封装axios
// http.js
import axios from 'axios'
import { Loading, Toast } from 'vant';
export function fetch(url, params = {}, method = 'POST', { loading = true, ...config } = {}) {
if (!url) {
throw new Error('Url cannot be empty');
}
let isGet = method.toUpperCase() === 'GET',
toast = null;
if (loading) {
toast = Toast.loading({
duration: 0,
mask: true,
message: '加载中...'
});
}
return new Promise((resolve, reject) => {
axios({
url: url,
method,
params: isGet ? params : '',
data: isGet ? '' : params,
...config
}).then(rep => {
toast && toast.clear();
resolve(rep);
}, err => {
toast && toast.clear();
reject(err);
});
});
}
引用
// api.js
import fetch from './http.js';
export const loginApi = params => fetch('/login', {...params});
// Login组件
// ...
import loginApi from '@/api.js'
methods: {
onLogin() {
loginApi({
username: this.username,
passward: this.passward
}).then(res=>{
console.log(res)
})
}
}
以上就是axios的简单封装,针对不同需要axios的配置是不同的,有兴趣的小伙伴可以看看官网文档,了解更多配置信息