简体   繁体   English

react如何在不同组件中使用axios实例?

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

I have created an axios instance:我创建了一个 axios 实例:

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

and would like to use it on different components.并希望在不同的组件上使用它。 My webapp is secured with Keycloak and every request that goes to API, needs an authentication token.我的 web 应用程序使用 Keycloak 进行保护,并且每个发送到 API 的请求都需要一个身份验证令牌。 To get the token, I call the Keycloak method as follows:为了获取令牌,我调用 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)

When I do the request to the API server, I pass the token as Bearer token in the request header.当我向 API 服务器发出请求时,我将令牌作为不Bearer token传递到请求标头中。 To avoid passing the token on every request, can I use the intercepter right or what do I have to do?为了避免在每个请求上传递令牌,我可以正确使用拦截器还是我必须做什么?

One way to achieve this is as follows:实现此目的的一种方法如下:

Create a file with the following code snippet and name this httpService.js (choose the name of your choice).使用以下代码片段创建一个文件并将其命名为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
};

Now to use it in other parts of your application, add this import:现在要在应用程序的其他部分使用它,请添加以下导入:

import http from './httpService';

Example usage:用法示例:

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

The baseUrl and Authorization header will be automatically configured with every request.每个请求都会自动配置baseUrlAuthorization标头。

Axios default configuration can be modified, once you modify the defaults all the service call that made using axios will use the same configuration. axios 默认配置可以修改,一旦修改了默认值,所有使用 axios 进行的服务调用都会使用相同的配置。

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

Please refer to the official docs https://github.com/axios/axios#global-axios-defaults请参考官方文档https://github.com/axios/axios#global-axios-defaults

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

相关问题 如何使用实用程序 class 实例来反应不同的组件并防止重新初始化,并且所有组件上只使用一个实例 - How to use a utility class instance in react different components and prevent reinitialization and only one instance is used on all components 如何在React中的不同路径上使用组件? - How to use Components on Different Routes in React? react和axios如何使用不同的IP地址进行开发和生产 - how to use different IP address for development and production with react and axios React 在不同组件中使用 state - React use state in different components 在 React 中渲染组件时,如何使用一个 axios 请求的 output 作为另一个请求的依赖项? - How do I use the output of one axios request as a dependency for another when rendering components in React? 如何在不使用导出的情况下在不同组件中使用axios响应? - How do I use axios response in different components without using export? 如何在反应中使用 axios (post) - how to use axios (post) in react 如何对齐不同的反应组件? - How to align different react components? 在反应原生应用程序中使用 axios 实例中的 API 令牌 - Use API token in axios instance in react native app React Axios 实例:How to get Token from redux store to put it on my axios instance - React Axios instance : How to get Token from redux store to put it on my axios instance
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM