Axios sets the timeout period
axios.default.timeout=15000
Copy the code
Setting of the POST request header
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';Copy the code
Axios request interception
In the header of the request token to carry axios. Interceptors. Request. Use ((config) = > {const token = UserModule. Token; let needToken = token && token.length > 0; if (needToken) { config.headers.Authorization = token; } return config; });Copy the code
Axios responds to interception
Async (response) => {const {config} = response; If (Number(response.data.code) === 401) {userModule. LoginOut({message: i18n.common.loginExpierd}); return Promise.reject("error"); } const { data, config, headers } = response; If (isSimpleResponse(data) && Number(data? .code) ! == 200) { const error = new Error(data? .msg ?? "Unknown Error"); error.name = data.code.toString(); Message({Message: error. Message, // Message: "operation failed ", type: "warning", duration: 3 * 1000,}); return Promise.reject(error); } return response; }, async (error) => { let { data } = error.response; const config = error.config as AxiosRequestConfig; / / blob is wrong type blob need to transform the if (error. The response. Config. ResponseType = = = "blob") {data = await resolveBlobRsp (data); } if (typeof data === "string") { error.name = error.response.status.toString(); error.message = error.response.statusText; } else { error.name = data.status.toString(); error.message = data.message ?? `${error.name} ${data.error}` ?? "Unknown Error"; } Message({ message: error.message, type: "warning", duration: 3 * 1000, }); UserModule.ResetUser(); return Promise.reject(error); });Copy the code
Wrap the GET method
export function get(url,params){
return new Promise((resolve,reject)=>{
axios.get(url,{
params: params
}).then(res => {
resolve(res.data);
}).catch(err =>{
reject(err.data)
})
})
}
Copy the code
Wrap post method
import QS from 'qs'
export function post(url,params){
return new Promise((resolve,reject)=>{
axios.post(url, QS.stringify(params)).then(res => {
resolve(res.data);
}).catch(err =>{
reject(err.data)
})
})
}
Copy the code
Addendum 1: Serialize qs.stringify (params) with QS for post submitted arguments
- Serialization and deserialization
Serialization refers to the object ------->JSONString, deserialization refers to JSONString------>JSONObject or object. JSONString: 'age':'10'Copy the code
Additional: How the post submits data (the data submitted by the Post must be in the entity-body of the message, but it is not specified what encoding must be used)
- The default content-type attribute is Application/X-www-form-urlencode
Key1 =val1&key2=val2Copy the code
- multipart/form-data
It is used to upload file FormDataCopy the code
- application/json
The message body is a serialized json string {"title":"test","sub":[1,2,3]}Copy the code
You need to get the file name from the return header returned
The AXIos interface has the responseHook for asynchronous request processing time
- 1. Declare the hook function
Declare Module "axios" {interface AxiosRequestConfig {/** Whether to display a warning when an interface error occurs. The default is */ WARN. : boolean; /** return hook */ responseHook? : (res: AxiosResponse) => void; }}Copy the code
- 2. Call the hook function in the AXIos interceptor
axios.interceptors.response.use( sync (response) => { const { config } = response; // Handle the event hook if (config? .responseHook) { config.responseHook(response); }})Copy the code
- 3. Use hook functions when calling interfaces
ResponseHook: (RSP) => {exportTitle = getExportTitle(RSP, "***.xlsx"); Export function getExportTitle(RSP: AxiosResponse<any>, defaultTitle: string) { let exportTitle = rsp.headers["content-disposition"].split("=")? . [1]???? defaultTitle; exportTitle = decodeURI(exportTitle); // Decode return exportTitle; }Copy the code