简体   繁体   中英

How to use axios instance in different components in react?

I have created an axios instance:

const instance = axios.create({
  baseURL: 'https://example.io/api/',
  timeout: 1000
});

and would like to use it on different components. My webapp is secured with Keycloak and every request that goes to API, needs an authentication token. To get the token, I call the Keycloak method as follows:

    kc
        .init({onLoad: "login-required"})
        .then(authenticated => {
            if (kc.idToken === undefined) {
                return Promise.reject("Can not be authenticated")
            }
            return authenticated && root !== null ? start({authToken: kc.idToken}, root) : Promise.reject("Can not be authenticated")
        })
        .catch(console.log)

When I do the request to the API server, I pass the token as Bearer token in the request header. To avoid passing the token on every request, can I use the intercepter right or what do I have to do?

One way to achieve this is as follows:

Create a file with the following code snippet and name this httpService.js (choose the name of your choice).

import axios from 'axios';    

// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    config.headers.Authorization = `Bearer ${your_token}`;
    // OR config.headers.common['Authorization'] = `Bearer ${your_token}`;
    config.baseURL = 'https://example.io/api/';

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

export default {
  get: axios.get,
  post: axios.post,
  put: axios.put,
  delete: axios.delete,
  patch: axios.patch
};

Now to use it in other parts of your application, add this import:

import http from './httpService';

Example usage:

static getClient = (clientId) => {
    return http.get('/clients/' + clientId);
};

The baseUrl and Authorization header will be automatically configured with every request.

Axios default configuration can be modified, once you modify the defaults all the service call that made using axios will use the same configuration.

axios.defaults.headers.common['Authorization'] = `Bearer ${AUTH_TOKEN}`;

Please refer to the official docs https://github.com/axios/axios#global-axios-defaults

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM