axios header dynamically add token

solution:

Very simple, axios interceptor, before sending a request to read from the cache, no null (important).

Official website method:

axios.interceptors.request.use ( function (config) {
     // do something before sending a request 
    return config; 
  }, function (error) {
     // request to do something wrong 
    return Promise.reject (error); 
  }) ;

 

my question:

I have a package of http-based axios class (please add):

Axios from Import 'Axios' 
Import from Storage ' ../utils/storage ' 
Import from Vant ' Vant '
 // Import from QS' QS ' 
Import config {} from' ./config ' 

const Tips = {
     . 1:' I'm sorry, an error occurred ' 
} 

var instance = axios.create ({ 
    the baseURL: config.base_url 
}); 

// Chinese distortion solution 
// instance.defaults.headers.post [' the Type-the Content '] =' file application / X-WWW -urlencoded the -form; charset = UTF-. 8 '; 
// request interceptor initiated before use qs serialized string processing parameter transmission request 


// request intercepted before the hair, header added token 
instance.interceptors.request.use (RES => {
    res.headers.common['X-Token'] = storage.get('token') || ''
    return res;
});

class Http {

    // get 请求
    get(url, params) {
        const result = instance.get(url, { params: params })
        result.then(res => {
            if (res.data.message) {
                Vant.Toast.fail(res.message)
            }
        })
        return result
    }

    //post 请求
    post(url, params) {
        const result = instance.post(url, params)
        result.then(res => {
            //Request printed Debug 
            the console.log (RES)
             IF (res.data.message) { 
                Vant.Toast.fail (res.data.message) 
            } 
        }) 
        return Result 
    } 

    // send string type 
    postStr (url, params) { 
        headers const = {
             'the Content-type': 'file application / X-WWW-form-urlencoded' 
        } 
        return instance.post (URL, the params, headers) 
    } 

    // concurrent requests 
    All (Array, the callback) { 
        instance.all (Array ) 
            .then (axios.spread ( function (acct, PERMS) {
                the callback ({acct, PERMS}) 
                // two requests are now completed execution 
            })); 
    } 

    // show good error 
    show_error (ERROR_CODE) {
         IF ! ( ERROR_CODE) { 
            ERROR_CODE =. 1 
        } 
        const Tip = Tips [ERROR_CODE ] 
        Vant.Toast.fail (Tip) 
    } 

} 

Export the Http {}

 

Guess you like

Origin www.cnblogs.com/likewpp/p/11098314.html