目录
一.什么是axios
axios是基于promise(诺言)用于浏览器和node.js是http客户端。
二.axios的作用
axios主要是用于向后台发起请求的,还有在请求中做更多的可控功能。
特征:支持浏览器和node.js
支持promise
能拦截请求和响应
能转换请求和响应数据
能取消请求
自动转换JSON数据
浏览器支持防止CSRF(跨站)
查看更多详细说明:https://www.kancloud.cn/yunye/axios/234845
三.封装与使用
1.封装fetch.js
import axios from 'axios';//引入axios
import qs from 'qs';// 序列化请求数据,视服务端的要求
import {Indicator, MessageBox, Toast} from 'mint-ui'; //引入提示工具
export function fetch(options) {
return new Promise((resolve, reject) => {
//instance创建一个axios实例,可以自定义配置,所有的请求都会带上这些配置,比如全局都要用的身份信息等。
const instance = axios.create({
baseURL: process.env.API_ROOT,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
timeout: 30 * 1000 // 30秒超时
});
//请求拦截器
instance.interceptors.request.use((options) => {
//1.加载动画
Indicator.open();
//2.是否带上token
//3.是否需要序列化数据
if (options.method.toLocaleLowerCase() === 'post') {
options.data = qs.stringify(options.data);
}
return options;
}, (error) => {
//1.关闭动画
Indicator.close();
//2.判断请求超时
//3.重定向到错误页面
return Promise.reject(error);
});
//响应拦截器
instance.interceptors.response.use(
res => {
Indicator.close();
return res;
},
error => {
Indicator.close();
if(error && error.response){
switch (error.response.status) {
case 404:
error.message = `请求地址出错: ${err.response.config.url}`;
break
case 500:
MessageBox.alert('服务器异常,请稍后重试', '错误提示');
break;
default:
error.message = `请求错误`
}
}
}
);
instance(options)
.then(response => { //then 请求成功之后进行什么操作
if (response) {
resolve(response.data);
}else {
resolve(response);
}
})
.catch(error => {
console.info('请求异常,信息:', error);
Toast('获取数据失败,请稍后重试');
reject(error);
});
});
}
2.封装api.js
import {fetch} from "../axios/fetch"; //引用fetch.js
import api from './url'; //引用url.js 统一写请求地址
function getSonCategoryList(categoryId) {
return fetch({
url: api.getSonCategoryList,
method: 'POST',
params: {categoryId}
})
}
function getCategory(data) {
return fetch({
url: api.getCategory,
method: 'POST',
params: data
})
}
export default{
getSonCategoryList,
getCategory
}
3.main.js --->全局注册api
import axios from "axios";
import APIUtils from './api/api';
Vue.prototype.$http = axios;
Vue.prototype.APIUtils = APIUtils;//全局API
4.使用
this.APIUtils.getCategory().then(
(res) => {
if (res.code == 200 ) {
doSomething();
}else{
doSomething();
}
});
如果不使用全局的方法,则在使用页import对应api即可。
import { getCategory} from './api/api'
getCategory().then(
(res) => {
if (res.code == 200) {
doSomething();
}else{
doSomething();
}
});