vue: axios secondary packaging, unified storage interface

1. Framework-based: vue
2. Based on http library: axios
Basic usage:
Installation via node:

npm install axios

2. Create a new providers folder under the src folder of the project directory and a new http-service.js file in the folder, which contains the following code blocks:

import axios from 'axios';

axios.defaults.timeout = 5000;
axios.defaults.baseURL ='http://www.baidu.com'; //Fill in the domain name

//http request interceptor
axios.interceptors.request.use(
  config => {
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);

//Response interceptor, exception handling
axios.interceptors.response.use(response => {
    return response
}, err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
            console.log('Error request')
          break;
        case 401:
            console.log('Unauthorized, please login again')
          break;
        case 403:
          console.log('access denied')
          break;
        case 404:
          console.log('Request error,The resource was not found')
          break;
        case 405:
          console.log('Request method not allowed')
          break;
        case 408:
          console.log('request timeout')
          break;
        case 500:
          console.log('Server-side error')
          break;
        case 501:
          console.log('Network not implemented')
          break;
        case 502:
          console.log('network error')
          break;
        case 503:
          console.log('Service unavailability')
          break;
        case 504:
          console.log('Network Timeout')
          break;
        case 505:
          console.log('http Version does not support this request')
          break;
        default:
          console.log(`Connection error ${err.response.status}`)
      }
    } else {
      console.log('Failed to connect to server')
    }
    return Promise.resolve(err.response)
})


/**
 * Encapsulation get method
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * Encapsulating post requests
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data = {}){
   return new Promise((resolve,reject) => {
     axios.post(url,data)
          .then(response => {
            resolve(response.data);
          },err => {
            reject(err)
          })
   })
 }

 /**
 * Encapsulating patch requests
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * Encapsulating put requests
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

/**
* Here's the interface for getting data
*/
/** 
* Test interface
* Name: exam
* Parameter: paramObj/null
* Method: fetch/post/patch/put
*/
export const server = {
    exam: function(paramObj){
        return post('/api.php?ac=v2_djList',paramObj);
    }
}

3. Refer to the above http-service.js file in main.js:

import {server} from './providers/http-service'

//Define global variables
Vue.prototype.$server=server;

IV. Test cases

export default {
  methods:{  
    exam: function(){
      let paramObj = {
        uid: '123456'
      }
      this.$server.exam(paramObj).then(data => {
        console.log(data)
      })
    }
  }
}

On the basis of the encapsulation method written by netizens, some modifications have been made. At present, it is used in the Componentization of its own project. If there is something wrong with it, you are welcome to leave a message pointing out.~

 

 

Want to learn front-end partners, you can pay attention to + private letter reply "information" free access oh~

Thank you for reading! Like can collect and forward oh~

Tags: Programming axios network npm JSON

Posted on Tue, 08 Oct 2019 17:52:14 -0700 by teege84