Introduction and use of axios

 

Features: Supports promise API, intercepts the request and response data and response data conversion request, cancellation request, automatically convert JSON data, client support defense XSRF the like;


After acquiring the data get, post submit data (for file uploads and form submission), patch update (only modified data is pushed to the rear end), put update (all data pushed to: axios request method (on the rear end defined) end), delete delete data


For example: axios_test.vue:

<script>
  export default{
  name:'axios_test',
  components:{},
  created(){
      //get
      axios.get('/data.json',{params:{id:12,name:'zs'}}).then((res)=>{
          console.log(res);
      })
  Or: axios ({
          method:'get',
          url:'/data.json',
          params:{
              id:12,
              name:'zs'
          }
      }).then((res)=>{
          console.log(res);
      })
      // POST 
      axios.post ( '/ xxx' ) .then ({
            // the default application / json common, there is no time for uploading files, use ibid unknown wrote 
           // form-submit the Data Form (for file uploads) 
          the let ID = {Data: 12 is }   
          let formData = new FormData()
          for(let key in data){
              formData.append(key,data[key]);
          }
          axios.post('post',formData).then(res=>{
              console.log(res)
          })
      })
      //put/patch
      axios.put('/put',data).then(res=>{
          console.log(res);
      })
      // Delete 
      Axios. Delete ( '/ Delete', the params {: {ID: 12 is}}). The then (RES => {})     // actually low-level calls get request, params data to be added to the url; 
      Axios. Delete . ( '/ Delete', {data: ID {:}} 12 is) the then (RES => {})     // actually calling the underlying post request, data on the data request body; 
      // concurrent requests simultaneously: a plurality of requests, and returns the unitary value. axios.all () and axios.spread () 
      axios.all ([
          axios.get('/data.json'),
          axios.get('/city.json')
      ]).then(
          axios.spread((dataRes,cityRes)=>{
              console.log(dataRes,cityRes);
          })
      )

      // Create axios instance 
      ({instance the let = axios.create   // the previous settings will override 
          the baseURL: 'HTTP: // localhost: 8080' ,
          timeout:1000,
          url:'/data.json',
          method:'get/post/put/patch/delete',
          headers: {token: ''},   // setting request header 
          the params: {}, // request parameters spliced to URL 
          Data: {}   // request into the request body parameters 
      })
      let instance2 = axios.create() 
      instance.get('/data.json').then(res=>{})
      //1、axios全局配置
        axios.defaults.timeout = 1000;
        axios.defaults.baseURL = 'HTTP: // localhost: 8080'
       // 2, Axios instance configuration (conventional manner) 
        the let instance axios.create = ()     // Create a global preventing contamination alone 
        instance.defaults.timeout = 3000   // other settings separately provided to prevent the cover 
      // . 3, Axios request configuration (three ways highest priority) 
        instance.get ( '/ the data.json' , {
           time:5000
        })

      @ Blockers: intercepting a request or response before they are processed, and a response is divided into the request interceptor interceptor 
        // request interceptor 
        axios.interceptors.request.use (config => {
             // do something before sending request 
            return config
          }, ERR => {
             // how to deal with an error occurs during request 
            return Promise.reject (ERR)
        })
        // response blocker 
        axios.interceptors.response.use (config => {
             // request success response data do processing 
            return RES
          }, ERR => {
             // how to deal with an error occurs in response to 
            return Promise.reject (ERR)
        })
        // cancel interceptor (understand) 
        the let Interceptor = axios.interceptors.request.use (config => {
            config.headers={ auto:true}
            return config
        })
        axios.interceptors.request.eject(interceptor);
        // interceptor Example 1: For example, you need to log microblogging review 
        the let instance = axios.create ({})
        instance.interceptors.request.use(config=>{
            config.headers.token = '';
            return config
        })
        // 2 interceptors example: request the mobile terminal to wait for the development of 
        the let instance_phone = axios.create ({})
        instance_phone.interceptors.request.use(config=>{
            $ ( '#Modal'). Show ()   // request waiting pop 
            return config
        })
        instance_phone.interceptors.response.use(res=>{
            $ ( '#Modal'). Hide ()   // request to wait for pop hidden 
            return RES
        })
      // error handling actual development, the general added unified error handling, special added separately. 
        // add request interceptor error handling 
        the let instance = axios.create ({})
        instance.interceptors.request(config=>{
            return config
        }, ERR => {
           // request error status codes generally begin with http 4, common: timeout 401, 404 did not find 
          $ ( '# Modal' ) the .Show ()
          setTimeout(()=>{
              $('#modal').hide()
          },2000)
            return Promise.reject(err)
        })
        // add error handling response blocker 
        instance.interceptors.response (RES => {
             return RES
        }, ERR => {
           // response to an error status code beginning with http Usually 5, common: system error 500, 502 system restart 
          $ ( '# Modal' ) the .Show ()
          setTimeout(()=>{
              $('#modal').hide()
          },2000)
            return Promise.reject(err)
        })
        // add special error handling 
        instance.get ( '/ the data.json'). The then (RES => {
            console.log(res)
        }).catch(err=>{
            console.log(err)
        })          
      // cancellation request (understand) 
        the let Source = axios.CancelToken.source ()
        axios.get('data.json',{cancelToken:source.token}).then()
        source.cancel ( 'the Cancel HTTP')   // cancellation request (message optional) 
        such as when users query the data takes too much time, users no longer have a query may be used when other operations, usually with less.
        
      }
    }
</script>

 

axios combat: the mobile terminal using a UI vant and axios package:


I Vant ①npm
②npm TS-I-Import plugin -D
③ quick start in accordance with API documentation tips, disposed in the babel.config.js

    module.exports = {
        plugins: [
            ['import', {
               libraryName: 'vant',
               libraryDirectory: 'es',
               style: true
           }, 'vant']
        ]
    };

 

④ introduced Vant components

test.vue:
<template> <van-button type="default">默认按钮</van-button> </template> <script> import axios from 'axios' import {Button} from 'vant' export default { name:'showlist', components:{ [Button.name] = the Button // locally registered, there is no time to write a reference template template, vant official format. }, created(){ axios.get(./data.json).then((res)=>{ console.log(res) }) } } </script>

 

⑤ router.js add a route: {path: '/ ShowList', name: '', Component: () => Import ( './ views / showlist.vue')}
⑥ NPM RUN serve to start the service test

axios of package example

①contactApi.js:

CONTACT_API const = {
  // get list of contacts 
getContactList: {
   method:'get',
   url:'/contactList'
 },
 // contacts form-data new 
newContactForm: {
   method:'post',
   url:'/contact/new/form-data'
 },
 // New contact the Application / json 
newContactJson: {
   method:'post',
   url:'/contact/new/json'
 },
 // Edit contact 
editContact: {
   method:'put',
   url:'/contact/edit'
 },
 // delete contacts 
delContact: {
   method:'delete',
   url:'/contact'
 },
}
export default CONTACT_API 

②http.js:

Axios from Import 'Axios' 
Import-Service from './contactApi.js' 
Import Toast {} from 'Vant'
 // -Service loop traversal, different output request method 
the let instance = axios.create ({
   baseURL: 'http: // localhost: 9000 / api' ,
   timeout:1000
})
the Http const = {}; // storage container request method 
for (the let Key in -Service) {
   let api = service[key];  //url、method
   Http[key] = async function(
       the params, // request parameter 
       isFormData = to false , // identifies whether the request is a form-data 
       config = {} // configuration parameter 
   ) {                        
       let newParams = {}
       if(params && isFormData){
           newParams = new FormData()
           for(let i in params){
               newParams.append(i,params([i]))
           }
       }else{
           newParams = params
       }
       // different requests determination of 
       the let Response = {}; // return the requested value 
       IF (api.method === 'PUT' || api.method === 'POST' || api.method === 'Patch ' ) {
            the try {Response = the await instance [api.method] (api.url, newParams, config)
           }catch(err){
               response = err
           }
       }else if(api.method ==='delete'||api.method==='get'){
           config.params = newParams
           try{ 
               response = await instance
               [api.method](api.url,config)
           }catch(err){
               response = err
           }
       }
       return response;
     }
 }
 // add interceptor 
 instance.interceptors.request.use (config => {
   Toast.loading({
     mask: false , // whether there is a shadow 
     DURATION: 0,   // there has been 
     forbidClick: to true ,   // prohibit click 
     message: 'Loading ...'
   })
   return config
  },err=>{
   Toast.clear()
   Toast ( 'request error, please try again later' )
 })
 // response blocker 
 instance.interceptors.response.use (RES => {
    Toast.clear()
    return res.data
 },()=>{
    Toast.clear()
    Toast ( 'request error, please try again later' )
 })
 export default Http

③main.js document introduced into http.js, and mount it on vue instance, after the introduction of added as follows:
 . Vue.prototype $ http = http;
④vue components used:
<script>
   import axios from 'axios'
   import {Button} from 'vant'
   export default {
     name:'showlist',
     components:{
       [Button.name] = the Button    // locally registered, there is no time to write a reference template template. 
     },
     methods:{
       // get list of contacts 
       async getList () {
         let res = await this.$http.getContact()
         this.list = res.data
       }
     }
     
   }
</script>

 

Guess you like

Origin www.cnblogs.com/mengzhongfeixue/p/11839419.html