Secondary encapsulation of AXIOS is performed in the project

With the development of front-end technology, more and more programs choose to use AXIOS to realize network requests. However, the axiOS plug-in alone is not enough for our daily use, so when we use it, we need to re-wrap AXIOS according to the actual situation of the project.

I’ll go into details about the secondary wrapping of AXIos, including before the request, returning the response, and using it.

1. Before the request

In the request header of the interface, we need to carry the token value to pass the authentication of the server. But if you add it every time you request it, not only does it add a lot of work, but it’s also very error-prone. Fortunately, Axios provides an interceptor mechanism, and we can add tokens to the interceptor of the request.

// Request interceptionaxios.interceptors.request.use((config) => {
/ /... Omit code  config.headers.x_access_token = token
  return config
}, function (error) {  return Promise.reject(error) }) Copy the code

Of course, in the request interceptor, besides adding tokens, it can also carry out some other processing according to actual requirements.


2. After the response

Request interface, not every request will be successful. What happens when an interface request fails? Each time it is requested? Encapsulate AXIOS unified processing? I think a coder with a little bit of code quality will choose to encapsulate AXIos for unified processing. Axios not only provides an interceptor for the request, it also provides an interceptor for the response. Here, you can obtain the status code returned by the server, and then perform corresponding operations according to the status code.

// Response interceptionaxios.interceptors.response.use(function (response) {
  ifResponse.data.code === 401) {// The user's token is invalid// Clear user information    sessionStorage.user = ' '
 sessionStorage.token = ' '  window.location.href = '/'; // Return to the login page returnPromise. Reject (MSG)// The interface Promise returns an error state. MSG can be returned by the back end, or we can define a code-message relationship. }  if(response.status! ==200||response.data.code! ==200){// The interface request failsmessage.error(msg); // An error message is displayed returnPromise.reject(MSG)// The interface Promise returns an error status }  return response }, function (error) {  if (axios.isCancel(error)) {  requestList.length = 0  // store.dispatch('changeGlobalState', {loading: false})  throw new axios.Cancel('cancel request')  } else {  message.error('Network request failed, please try again')  }  return Promise.reject(error) }) Copy the code

Of course, the response interceptor, like the request interceptor, can also do some other processing, depending on the actual needs of the processing.


3. Use Axios

Axios is used in one of three ways:

  • Performing a GET request
axios.get('url', {Params :{},// Interface parameters}).then(function(res){
console.log(res); // A function that handles success is equivalent to success}).catch(function(error){
Console. log(error)// Error handling is equivalent to error}) Copy the code
  • Performing a POST request
axios.post('url', {Data: XXX / / parameters}, {Headers: XXXX,// Request header information}).then(function(res){
console.log(res); // A function that handles success is equivalent to success}).catch(function(error){ Console. log(error)// Error handling is equivalent to error}) Copy the code
  • The AXIos API completes the request by passing the relevant configuration to AXIos
axios({
  method:'delete'.  url:'xxx'.  cache:false.  params:{id:123},
 headers:xxx, }) //------------------------------------------// axios({  method: 'post'. url: '/user/12345'. data: {  firstName: 'monkey'. lastName: 'soft'  } });  Copy the code

Although it is simple to use the API directly, different request parameters have different names, which can easily be miswritten or ignored in the actual development process, resulting in unnecessary time loss for development.

Although the first two methods have no problem with inconsistent parameters, they are too troublesome to use. So what to do?

Although the first two are too troublesome to use, it can be found that there are certain similarities after careful observation. Based on these similarities, we can form a request function suitable for our use. Directly on the code:

/ ** URL: The requested URL*params: Request parameters*config: header information in the request*method: request method* /const request = function ({ url, params, config, method }) { // If it is a GET request, concatenation parameters are required let str = ' '  if (method === 'get' && params) {  Object.keys(params).forEach(item => {  str += `${item}=${params[item]}& ` })  }  return new Promise((resolve, reject) => {  axios[method](str ? (url + '? ' + str.substring(0, str.length - 1)) : url, params, Object.assign({}, config)).then(response => {  resolve(response.data)  }, err => {  if (err.Cancel) {  } else {  reject(err)  }  }).catch(err => {  reject(err)  })  }) } Copy the code

This way we can call this function directly when we need an interface request. Regardless of the request mode, the parameter transmission method is the same. Finally, if you want to discuss the exploration front end with me, you can pay attention to my public account, update dry goods from time to time, and join the technical group exchange and discussion.

This article is formatted using MDNICE