创建 Axios 实例时,在我的例子中如何从异步存储分配值
When create Axios instance, how to assign value from async storage in my case
在我的 react-native 项目中,我使用 async-storage
来存储授权令牌。我使用 Axios
作为 HTTP 客户端库,当我设置 header 时,如果没有存储值,我想使用空字符串作为 header Authorization
的值在 AsyncStorage
。否则使用存储中的值。
下面是我试过的代码,但我无法理解如何放置用于从存储中获取值的代码,因为它是一个 await
调用。我不能像现在这样说,编译器抱怨道。但是export axios在文件中是一个object。那么,有什么建议吗?
import AsyncStorage from '@react-native-community/async-storage';
import {STORAGE_KEYS} from '../constants';
// I can't put this line here
const myToken = await AsyncStorage.getItem(STORAGE_KEYS.MyToken);
export default Axios.create({
baseURL: 'http://192.168.10.207:3000',
headers: {
Authorization: myToken ? myToken : '',
},
});
Axios 拦截器
一种解决方案是使用 Interceptors
:
https://github.com/axios/axios#interceptors
import AsyncStorage from '@react-native-community/async-storage';
import {STORAGE_KEYS} from '../constants';
import axios from 'axios;
const instance = return axios.create({ baseURL: 'http://192.168.10.207:3000' });
instance.interceptors.request.use(async function (config) {
const myToken = await AsyncStorage.getItem(STORAGE_KEYS.MyToken);
config.headers['Authorization'] = myToken ? myToken : '';
return config;
});
export default instance;
(未测试)
在我的 react-native 项目中,我使用 async-storage
来存储授权令牌。我使用 Axios
作为 HTTP 客户端库,当我设置 header 时,如果没有存储值,我想使用空字符串作为 header Authorization
的值在 AsyncStorage
。否则使用存储中的值。
下面是我试过的代码,但我无法理解如何放置用于从存储中获取值的代码,因为它是一个 await
调用。我不能像现在这样说,编译器抱怨道。但是export axios在文件中是一个object。那么,有什么建议吗?
import AsyncStorage from '@react-native-community/async-storage';
import {STORAGE_KEYS} from '../constants';
// I can't put this line here
const myToken = await AsyncStorage.getItem(STORAGE_KEYS.MyToken);
export default Axios.create({
baseURL: 'http://192.168.10.207:3000',
headers: {
Authorization: myToken ? myToken : '',
},
});
Axios 拦截器
一种解决方案是使用 Interceptors
:
https://github.com/axios/axios#interceptors
import AsyncStorage from '@react-native-community/async-storage';
import {STORAGE_KEYS} from '../constants';
import axios from 'axios;
const instance = return axios.create({ baseURL: 'http://192.168.10.207:3000' });
instance.interceptors.request.use(async function (config) {
const myToken = await AsyncStorage.getItem(STORAGE_KEYS.MyToken);
config.headers['Authorization'] = myToken ? myToken : '';
return config;
});
export default instance;
(未测试)