axios react-keycloak/web 拦截器中的标记

axois react-keycloak/web token in inteceptor

我正在尝试将请求拦截器与 react-keycloak/web 一起使用 - 但是我在这样做时遇到了一系列错误。

import axios from 'axios';
import { useKeycloak } from '@react-keycloak/web';

const { keycloak } = useKeycloak();

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

instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `${keycloak.token}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

但我得到:

React Hook "useKeycloak" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks

现在我当然尝试创建一个函数,例如 GetToken():

function GetToken() {
  const { keycloak } = useKeycloak();
  return keycloak.token
}

但这样做给我留下了:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

我做错了什么?

你不能使用反应树之外的反应钩子。

您可以导出 axoios 实例并将其导入 react 中的其他位置(例如:App.js)并在那里设置拦截器。

例如:

import axiosIns from 'api';
import { useKeycloak } from '@react-keycloak/web';
import { useEffect } from "react";
import WholeApp from "WholeApp";

const App = () => {
    const { keycloak } = useKeycloak();

    useEffect(() => {
        axiosIns.interceptors.request.use(
            (config) => {
                config.headers.Authorization = `${keycloak.token}`;
                return config;
            },
            (error) => {
                return Promise.reject(error);
            }
        );
    }, []);

    return <WholeApp />;
}