创建Axios实例时,在我的情况下如何从异步存储分配值

问题描述

在我的本机项目中,我使用async-storage来存储授权令牌。我将Axios用作HTTP客户端库,设置标头时,如果Authorization中没有存储值,我想使用空字符串作为标头AsyncStorage的值。否则,请使用存储中的值。

下面是我尝试过的代码,但是由于它是一个await调用,因此我在如何放置用于从存储中获取值的代码方面陷入了困境。我不能像现在这样说,编译器抱怨。但是导出Axios是文件中的对象。那么,有什么建议吗?

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拦截器

一种解决方案是使用Interceptorshttps://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; 

(未经测试)