/**
* request network request tool
* More detailed api documentation: /umijs/umi-request
*/
import { extend } from 'umi-request';
import { notification, message } from 'antd';
import { getDvaApp } from 'umi'
/**
* Default parameters when configuring request request
*/
const request = extend({
credentials: 'include', // Whether to bring cookies by default
});
// Request for interception
request.interceptors.request.use(async (url, options) => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Control-Allow-Origin': '*'
}
if (['post', 'put', 'delete'].indexOf(options.method) > -1) {
if (!(options.body instanceof FormData)) {
headers['Content-Type'] = 'application/json; charset=utf-8'
options.body = JSON.stringify(options.body)
}
}
const token = localStorage.getItem('react-token')
headers.Authorization = `Bearer ${token}`
return {
url,
options: { ...options, headers }
}
})
// Return to intercept
request.interceptors.response.use(async res => {
const response = await res.clone();
const codeMaps = {
400: 'The request was issued with an error, and the server did not perform new or modified data operations. ',
// 401: 'The user does not have permissions (incorrect token, username, password). ',
403: 'The user is authorized, but access is prohibited. ',
404: 'The request is issued for non-existent records and the server does not operate. ',
406: 'The requested format is not available. ',
410: 'The requested resource is permanently deleted and will not be obtained again. ',
422: 'When an object is created, a validation error occurs. ',
500: 'An error occurred on the server, please check the server. ',
502: 'Gateway error. ',
503: 'The service is not available, the server is temporarily overloaded or maintained. ',
504: 'Gateway timed out. ',
};
if (response.status === 401) {
notification.error({
message: response.message || 'Not logged in or the login has expired, please log in again. ',
duration: 3000,
})
localStorage.clear()
setTimeout(() => {
// Jump login
getDvaApp()._store.dispatch({
type: 'login/logout',
})
}, 3000);
return false
}
if (codeMaps[response.status]) {
notification.error({
message: `Request error${response.status}`,
description: codeMaps[response.status]
})
return false
}
return response;
});
export default request;