Attach Authorization header for all axios requests

前端 未结 9 1993
灰色年华
灰色年华 2020-12-04 05:17

I have a react/redux application that fetches a token from an api server. After the user authenticates I\'d like to make all axios requests have that token as an Authorizati

9条回答
  •  清歌不尽
    2020-12-04 05:31

    The best solution to me is to create a client service that you'll instantiate with your token an use it to wrap axios.

    import axios from 'axios';
    
    const client = (token = null) => {
        const defaultOptions = {
            headers: {
                Authorization: token ? `Token ${token}` : '',
            },
        };
    
        return {
            get: (url, options = {}) => axios.get(url, { ...defaultOptions, ...options }),
            post: (url, data, options = {}) => axios.post(url, data, { ...defaultOptions, ...options }),
            put: (url, data, options = {}) => axios.put(url, data, { ...defaultOptions, ...options }),
            delete: (url, options = {}) => axios.delete(url, { ...defaultOptions, ...options }),
        };
    };
    
    const request = client('MY SECRET TOKEN');
    
    request.get(PAGES_URL);
    

    In this client, you can also retrieve the token from the localStorage / cookie, as you want.

提交回复
热议问题