在所有 Axios 请求上使用 Auth0 React Hook

Using Auth0 React Hook on all Axios requests

我已经按照他们的快速入门教程使用 React 设置了 Auth0。
基本上我的 React 应用程序围绕着他们的上下文提供者,我可以访问我的任何组件中的 useAuth0 挂钩。

这就是我向 API 发出请求的方式:

const TestComponent = () => {
  const { getTokenSilently } = useAuth0();

  const getObjectsFromAPI = async () => {
    const token = await getTokenSilently();
    const axiosConfig = {
      headers: {
        Authorization: "Bearer " + token
      }
    };

    const response = await axios.get(
      "/api/objects/",
      axiosConfig
    );

    // ... do something with the response

  };

  return ... removed code for brevity
};

有没有一种方法可以发出请求而不必在每个请求上写 tokenaxiosConfig

我知道我可以使用配置初始化一个新的 axios 实例,但是我不能在 Context Provider 之外使用 useAuth0 挂钩。

but I cannot use the useAuth0 hook outside the Context Provider.

是的,不确定如何避免每次请求生成令牌,但您可以通过将令牌传递给共享的 axios 实例来保存 axios 配置部分,例如:

http.js

const instance = axios.create({
  // your config
});

export const authorized = (token) => {
   instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
   return instance;
}

在你的组件中:

import http from '/path/to/above/http.js';

const TestComponent = () => {
  const { getTokenSilently } = useAuth0();

  const getObjectsFromAPI = async () => {
    const token = await getTokenSilently();

    const response = await http
       .authorized(token)
       .get('/api/objects/');

    // ...
  };
};