问题:
在我的react本机应用程序中,为了消除重复的呼叫,我在httpClient文件中开发了一个常规的POST GET方法。它的代码看起来像这样。
List<UserRepresentation> search = getKeycloakInstance().realm("my-realm").users()
.search("username");
有人可以告诉我一种向此实例添加授权标头的方法吗?我的令牌将Asyncstorage存储在某些操作的中间,因此在开始时我没有令牌。由于我的代码setHeader仅运行一次,因此我创建了一个方法调用setAuthorisationHeder()函数。但这给了我找不到属性.then的错误,当我提出一个请求。有人可以帮我解决这个问题吗?谢谢吗?
答案 0 :(得分:0)
you can define global headers once and use it in every network call.
答案 1 :(得分:0)
创建一个全局auth变量,您将在其中存储来自存储的auth数据。在发出请求之前,请获取auth数据,并使用拦截器设置承载令牌。
let authToken = '';
const getAuthToken = async () => {
// asumming auth token was saved as string
authToken = await AsyncStorage.getItem('auth_data');
};
拦截器
// request interceptor
axiosInstance.interceptors.request.use(
function (config) {
// Do something before request is sent
config.headers.Authorization = `Bearer ${authToken}`;
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
完整代码
import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';
let authToken = '';
const axiosInstance = axios.create({
baseURL: '',
timeout: 150000,
headers: {
'Content-Type': 'application/json',
},
});
// request interceptor
axiosInstance.interceptors.request.use(
function (config) {
// Do something before request is sent
config.headers.Authorization = `Bearer ${authToken}`;
return config;
},
function (error) {
// Do something with request error
return Promise.reject(error);
}
);
const getAuthToken = async () => {
// asumming auth token was saved as string
authToken = await AsyncStorage.getItem('auth_data');
};
export const Get = async (route, data = {}) => {
// get and set auth token
await getAuthToken();
// route = /user?id=787878 or /user/787878
return await axiosInstance.get(route);
};
export const Post = async (route, data = {}) => {
await getAuthToken();
return await axiosInstance.post(route, data);
};