【问题标题】:How to use axios instance in different components in react?react如何在不同组件中使用axios实例?
【发布时间】:2020-11-04 12:38:56
【问题描述】:

我已经创建了一个 axios 实例:

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

并希望在不同的组件上使用它。 我的 webapp 使用 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 传递。为避免在每个请求上传递令牌,我可以使用intercepter 权限还是我必须做什么?

【问题讨论】:

  • 我认为实例部分很好。你只需要使用拦截。您似乎已经在管理令牌。在拦截器中简单调用并在那里使用它。

标签: reactjs axios


【解决方案1】:

实现此目的的一种方法如下:

使用以下代码创建一个文件 sn-p 并将其命名为 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 标头将随每个请求自动配置。

【讨论】:

    【解决方案2】:

    可以修改axios默认配置,一旦修改了默认配置,所有使用axios进行的服务调用都将使用相同的配置。

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

    请参考官方文档https://github.com/axios/axios#global-axios-defaults

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2017-06-23
      • 2021-11-13
      相关资源
      最近更新 更多