api request function based on axios encapsulation

After vue resource is not recommended in vue 2.0, most people choose axios. axios can be used not only in vue, but also in angular and react. So learning to use it will always work.

If you don't know how to use it, take a look at this article: https://www.kancloud.cn/yunye/axios/234845.

If every request is completely and completely written once, it will look like this:

axios.get('/user?ID=12345')

  .then(function (response) {

    if (response.data.code === 200) {

        //Request executed successfully

    } else {

        // Wrong execution statement

    }

  }).catch(function (error) {

       // An error thrown by a network or server

     alert(error.toString())

  })

Well, it doesn't seem very complicated, but this code fixes the config configuration of axios, including methods, paths, header [content type], etc. These need to be changed constantly in the same project. Therefore, we can write a function which is the easiest for us to make a request quickly.

function fetch(method, url, params, type,contentType) {
  if (type == 'json') {
    typeHttp = type;
  } else {
    typeHttp = ''
  }
  return new Promise((resolve, reject) => {
    switch (method) {
      case 'post':
        if (contentType === 'json') {
          axios.post(url, params,{
            headers: {
              'Content-Type': 'application/json',
            }
          })
            .then(response => {
              typeHttp = '';
              resolve(response.data);

              //Judge whether there is a picture or not, and do not put the default picture
              if (response.data.code == '200') {
                _.imgdefauilt();
              }
            }, err => {
              typeHttp = '';
              reject(err);
            })
            .catch((error) => {
              typeHttp = '';
              reject(error)
            })
        }else {
          axios.post(url, params,)
            .then(response => {
              typeHttp = '';
              resolve(response.data);

              //Judge whether there is a picture or not, and do not put the default picture
              if (response.data.code == '200') {
                _.imgdefauilt();
              }
            }, err => {
              typeHttp = '';
              reject(err);
            })
            .catch((error) => {
              typeHttp = '';
              reject(error)
            })
        }
        break;
      case 'get':
        axios.get(url)
          .then(response => {
            typeHttp = '';

            resolve(response.data);

            //Judge whether there is a picture or not, and do not put the default picture
            if (response.data.code == '200') {
              _.imgdefauilt();
            }
          }, err => {
            typeHttp = '';
            reject(err);
          })
          .catch((error) => {
            typeHttp = '';
            reject(error)
          })
        break;
      default:
        Message.error('method Error!');
        break;
    }
  })
}

Code as above, using the promise asynchronous function, we call the function and use. then () to execute the callback.

Example:

 //Call the fetch function
getTbCount(params) {
    return fetch('post', '/web/url', params);
  },


//External reference api and data processing (the advantage is that all APIs can be put in one file for easy maintenance)
api.getTbCount(params)
.then(res => {
   if (res.code && res.code == '200') {
      if (res.data) {
              //Successful callback
       }
    }  else {
              _.message('error',res.message);
              return false;
     }
})
.catch(err => {console.log(err, '0')});

 

Tags: axios Vue JSON angular

Posted on Fri, 03 Jan 2020 03:08:18 -0500 by ShashidharNP