简体   繁体   English

在反应原生应用程序中使用 axios 实例中的 API 令牌

[英]Use API token in axios instance in react native app

I am trying to create an axios instance that I can use throughout the app.我正在尝试创建一个可以在整个应用程序中使用的 axios 实例。 I used this same pattern in Vue using Vuex store but not sure how to do this in React.我使用 Vuex 商店在 Vue 中使用了相同的模式,但不确定如何在 React 中执行此操作。 I have an AuthProvider for AuthContext and would like to useContext when creating the axios instance but I'm receiving an error that I can't use useContext outside of a component.我有一个用于 AuthContext 的 AuthProvider,并且想在创建 axios 实例时使用 useContext,但我收到一个错误,即我无法在组件之外使用 useContext。

What is the best way to accomplish this?实现这一目标的最佳方法是什么? I have the user and a logout function in the AuthContext that I would like to use but this pattern may not be best for React.我在我想使用的 AuthContext 中有用户和注销 function,但这种模式可能不适合 React。

import React, { useContext } from "react";
import axios from 'axios'
import { AuthContext } from "./AuthProvider";
import { getEnvironment } from "./environment";
const env = getEnvironment();

const { user, logout } = useContext(AuthContext);

const instance = axios.create();

instance.defaults.baseURL = env.apiUrl;

instance.defaults.headers.common['Authorization'] = `Bearer ${user.token}`;

instance.interceptors.response.use(function (response) {
  return response
}, function (error) {
  if (typeof error.response === 'undefined' || [401, 419].includes(error.response.status)) {
    logout();
  }
  return Promise.reject(error)
})

export default instance;

I think if you want to couple some state and callbacks from another context then you need to create another context and axios instance provider of your own as well.我认为如果你想结合一些 state 和来自另一个上下文的回调,那么你需要创建另一个上下文和你自己的 axios 实例提供程序。

import React, { createContext, useEffect, useContext } from "react";
import axios from 'axios'
import { AuthContext } from "./AuthProvider";
import { getEnvironment } from "./environment";

const env = getEnvironment();

const instance = axios.create(); // <-- create axios instance
instance.defaults.baseURL = env.apiUrl;

export const AxiosContext = createContext(null); // <-- export axios context

const AxiosProvider = ({ children }) => {
  const { user, logout } = useContext(AuthContext); // <-- get state/callback

  // Use an effect to updated the auth context dependent details
  useEffect(() => {
    instance.defaults.headers.common['Authorization'] = `Bearer ${user.token}`;
    instance.interceptors.response.use(function (response) {
      return response
    }, function (error) {
      if (typeof error.response === 'undefined' || [401, 419].includes(error.response.status)) {
        logout();
      }
      return Promise.reject(error);
    });
  }, [user.token, logout]);
  

  return (
    <AxiosContext.Provider value={instance}> // <-- context value is instance
      {children}
    </AxiosContext.Provider>
  );
}

export default AxiosProvider; // <-- export the provider not the instance

To use just ensure that AxiosProvider wraps your application but within the auth provider.要使用只需确保AxiosProvider将您的应用程序包装在auth提供程序中。 Use the AxiosContext to access the axios instance.使用AxiosContext访问 axios 实例。

import { AxiosContext } from '../path/to/axios/instance";

...

const axiosInstance = useContext(AxiosContext);

...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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