[在我的ReactNative
应用程序中,我试图提供一个不错的模式来读取我存储在access_token
中的AsyncStorage
,并在fetch
调用中使用它。似乎我在Async
的AsyncStorage
部分遇到问题,并且我的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
中?
您可以在函数内添加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
}
})
}