[英]How to use a utility class instance in react different components and prevent reinitialization and only one instance is used on all components
[英]How to use axios instance in different components in react?
我创建了一个 axios 实例:
const instance = axios.create({
baseURL: 'https://example.io/api/',
timeout: 1000
});
并希望在不同的组件上使用它。 我的 web 应用程序使用 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
传递到请求标头中。 为了避免在每个请求上传递令牌,我可以正确使用拦截器还是我必须做什么?
实现此目的的一种方法如下:
使用以下代码片段创建一个文件并将其命名为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);
};
每个请求都会自动配置baseUrl
和Authorization
标头。
axios 默认配置可以修改,一旦修改了默认值,所有使用 axios 进行的服务调用都会使用相同的配置。
axios.defaults.headers.common['Authorization'] = `Bearer ${AUTH_TOKEN}`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.