在获取调用之前从AsyncStorage读取令牌

问题描述 投票:0回答:1

[在我的ReactNative应用程序中,我试图提供一个不错的模式来读取我存储在access_token中的AsyncStorage,并在fetch调用中使用它。似乎我在AsyncAsyncStorage部分遇到问题,并且我的fetch通话在没有令牌的情况下中断。

这是我的fetch电话:

export const someApiCall = (request) => {

   const url = 'https://myapi.com/add';

   return (dispatch) => fetch(url, fetchOptionsPost(request))
        .then((response) => {

            if (response.ok && response.status === 200) {

                // Got data. Dispatch some action

            }
        })
}

[这里,我正在使用辅助函数来准备标题,等等。这是fetchOptionsPost()的样子:

export const fetchOptionsPost = (request) => {

    getAccessToken()
        .then(token => {

            return {
                method: 'POST',
                mode: 'cors',
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": "Bearer " + token
                },
                body: JSON.stringify(request)
            }
       });
};

getAccessToken()函数仅从AsyncStorage读取它,如下所示:

export const getAccessToken = async () => {

    return await AsyncStorage.getItem("access_token");
}

此模式不起作用,API调用在没有令牌的情况下就消失了。我该怎么做才能确保我的令牌始终放在我的fetchOptionsPost中?

javascript react-native fetch asyncstorage
1个回答
0
投票

您可以在函数内添加token调用

export const someApiCall = async (request) => {
   const token = await AsyncStorage.getItem("access_token");
   const url = 'https://myapi.com/add';
   const options = {
            method: 'POST',
            mode: 'cors',
            headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer " + token
            }
          };
   return (dispatch) => fetch(url,options)
        .then((response) => {

            if (response.ok && response.status === 200) {

                // Got data. Dispatch some action

            }
        })
}
© www.soinside.com 2019 - 2024. All rights reserved.