簡體   English   中英

react如何在不同組件中使用axios實例?

[英]How to use axios instance in different components in react?

我創建了一個 axios 實例:

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

並希望在不同的組件上使用它。 我的 web 應用程序使用 Keycloak 進行保護,並且每個發送到 API 的請求都需要一個身份驗證令牌。 為了獲取令牌,我調用 Keycloak 方法如下:

    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)

當我向 API 服務器發出請求時,我將令牌作為不Bearer token傳遞到請求標頭中。 為了避免在每個請求上傳遞令牌,我可以正確使用攔截器還是我必須做什么?

實現此目的的一種方法如下:

使用以下代碼片段創建一個文件並將其命名為httpService.js (選擇您選擇的名稱)。

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
};

現在要在應用程序的其他部分使用它,請添加以下導入:

import http from './httpService';

用法示例:

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

每個請求都會自動配置baseUrlAuthorization標頭。

axios 默認配置可以修改,一旦修改了默認值,所有使用 axios 進行的服務調用都會使用相同的配置。

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

請參考官方文檔https://github.com/axios/axios#global-axios-defaults

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM