preface
In the front-end development, if the page needs to interact with the background interface, and no page refresh, then need to use the Ajax HTTP library to complete the docking work with the background data interface. This article will share our front-end team’s experience of encapsulating an HTTP library, Axios, with some scenarios from our team’s development projects
Basic encapsulation of Axios
- The basic framework of Request. ts
Import axios from 'axios const service = axios. The create () / / request interceptor service. The interceptors. Request. Use ((config) = > {}, (err) => {} ) service.interceptors.response.use( (res) => {}, (err) => {} ) const request = { get: () => service.get().then(resolve), post: () => service.post().then(resolve), } export default requestCopy the code
-
Interceptors. Request is handled by the interceptor code
Intercepting requests sets generic request headers, such as setting tokens
service.interceptors.request.use( (config) => { config.headers.token = sessionStorage.getItem('userToken') return config }, (err) => { if (! Response) {// In actual business scenarios, use the messe-related components in your own project or antd console.log(' request timed out, please try again later ')}})Copy the code
3. Interceptors. Use Interceptor code handling
The redirectToLogin method is usually used to determine the login state and redirect to the login page. The redirectToLogin method is not discussed further here
service.interceptors.response.use( (res) => { if (res.data.status) { let { code, RetCode} = res. Data. The status / / according to retCode | | code with the back-end agreement good shape code determine whether login, or other unexpected business scenario if (true) {redirectToLogin () return {data: {}, code: 1, MSG: 'unlogin ', status: res.data.status}}} return res.data}, (err) => {})Copy the code
-
Format processing of return values for generic requests
Any is often used in real world scenarios, but only to reduce the code length
function handleResponseFormat(response: any): any { const { data, status } = response if (! status) { return response } const RetCode = status.RetCode === undefined ? status.retCode : status.RetCode return { data, RetCode, msg: status.msg, success: status.RetCode === 0 || status.retCode === 0, status: { ... status, RetCode }, } }Copy the code
- Perfection of the Request object
const request = { get: (url: string, params? : object) => service.get(url,params).then(handleResponseFormat), post: (url: string, query: object) => service.post(url,query)).then(handleResponseFormat), }Copy the code
At this point, the basic encapsulation of request ends
API wrapper
-
Encapsulate interfaces with THE ES6 Module
Generally, our business modules are divided into several chunks, such as order, scheduling, setting, home page, etc., and export the corresponding file name :testApi separately according to the module
Import HTTP from '@http' export default {getInfo: (query:) import HTTP from '@http' any) => http.get('/... AddInfo: (query: {id:number}) => http.post('/... /info', body),}Copy the code
API service scenarios
Import {testApi} from '@api' const getsomethingDetailInfo =; // Select * from '@api' const getsomethingDetailInfo = async () => { const param={} const { data, Success, MSG} = await testapi.getInfo (param) if (success) {console.log(data)}else{// Replace the console here according to the actual UI component call Console. log(MSG)} const addsomething = async () => {// const param={} const {data, Success, MSG} = await testapi.addinfo (param) if (success) {console.log(data)}else{// Replace the console here based on the actual UI component call console.log(msg) }Copy the code
summary
Please give me your first summary
Finally, if you find this article helpful, remember to like it three times. Thank you very much!