Recently, I am working on a project with React. I used VUE a lot before, but I don’t know much about React. Please record the learning process. Because the framework uses Umi, its own network request library is Umi-Request, refer to ANTD-Pro, and write the encapsulation function of network request below.
Project background
- Use create Umi’s simple app template
- antd
Set the default parameters for the request request
/src/utils/request.js
import { extend } from 'umi-request';
import { getToken } from '@/utils/token';
const baseUrl = process.env.NODE_ENV === 'production' ? ' ' : '/api';
const request = extend({
errorHandler, // Default error handling
prefix: baseUrl,
// The default request header
headers: {
Authorization: getToken() ? `Bearer ${getToken()}` : null./ / carry a token
},
credentials: 'include'.// Whether cookies are included in the request by default
});
// code...
export default request;
Copy the code
Exception handler
const codeMessage = {
200: 'The server successfully returned the requested data. '.201: 'Creating or modifying data succeeded. '.202: 'A request has been queued in the background (asynchronous task). '.204: 'Deleting data succeeded. '.400: The server did not create or modify data. '.401: 'User has no permissions (wrong token, username, password). '.403: 'The user is authorized, but access is forbidden. '.404: 'The request was made for a nonexistent record, and the server did not act on it. '.406: 'Requested format not available. '.410: 'The requested resource is permanently deleted and will not be retrieved. '.422: 'A validation error occurred while creating an object. '.500: 'Server error, please check server. '.502: 'Gateway error. '.503: 'Service unavailable, server temporarily overloaded or maintained. '.504: 'Gateway timed out. '};const errorHandler = error= > {
const { response = {} } = error;
const errortext = codeMessage[response.status] || response.statusText;
const { status, url } = response;
notification.error({
message: 'Request error${status}: ${url}`.description: errortext,
});
};
Copy the code
This exception handler is to deal with the HTTP response status of the exception, that is, the status code is 4XX or 5XX, etc. If you want to customize the error code in the response body, it should be processed in the response interceptor, or use middleware.
Request interceptor
request.interceptors.request.use((url, options) = > {
return {
options: {
...options,
},
};
});
Copy the code
The request interceptor does nothing. I tried to override the configuration in options, such as modifying headers. Write the default argument at extend to take effect. You can change the URL here:
options: { ... options,url: '/v1'+url
},
Copy the code
The response of interceptors
request.interceptors.response.use(async response => {
// Clone the response object for parsing
// Where res is the requested data
const res = await response.clone().json();
const { code, message } = res;
if(code ! = =0) {
console.log('error', res);
notification.error({
message: 'Request error'.description: `${code}: ${message}`});// See if there is a value for res
return;
}
return res;
});
Copy the code
Note: To get Response.data, the Response object must be parsed. Response.clone ().json(); response.clone(); You can then handle errors according to your custom code. For example, you can set code===5008 to indicate that you are not logged in and then redirect to the login page; When the code! When ==0, an error message is displayed, and then return. When the request function is called, the corresponding code is executed after checking whether the result has a value. Finally, if no error handling is required, return res.
Some thoughts
React is much harder to learn than Vue, mainly because I’m too bad. Compared to Axios, umi-Request feels less intuitive and Axios writes interceptors. But if umi-Request’s middleware works well, the interceptor should be fine.