https://blog.csdn.net/qq_40128367/article/details/82735310
https://www.mmxiaowu.com/article/589af8cde9be1c5b21ef8e9c
![](https://leanote.com/api/file/getImage?fileId=5ea24dfeab644126a1042fee)
# 为什么要封装
---
## 1)配置通用项
## 2)统一处理请求错误,进行提示
# 请求流程
---
![](https://leanote.com/api/file/getImage?fileId=5ea24dfeab644126a1042fef)
## 请求失败
通常请求失败有两种原因:
### 1)网络问题或代码问题造成的400、500等错误
### 2)请求参数后端不通过验证,由后端抛出的错误
根据不同的后端框架或者程序员又可以分为两种:
一种是直接返回json,用一个特别的code来区别正常请求反悔的数据
```
{
code: -404,
message: '这是错误信息',
data: '',
}
```
另一种是抛出http 404之类的,然后把错误原因放在header里。
### 在组件写调用ajax时,通常都是这么写
```
import axios from 'axios'
axios.post('/user' , {
params: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function (response) {
// 处理响应
if(response.data.code === 200){
console.log(response.data)
} else {
// 其中存在后端返回的错误
}
})
.catch(function (error) {
// 网络异常引发的错误或服务器抛出的错误
console.log(error.toString())
});
```
我们知道,一般中大型规模的项目,请求是比较多的,这样导致代码冗余,会越来越臃肿,我们可以**对错误进行预处理。**
## 拦截器做预处理
### 请求时的拦截器
```
axios.interceptors.request.use(config => {
// 这里可以加一些动作, 比如来个进度条开始动作,
NProgress.start()
return config
}, error => {
return Promise.reject(error)
})<