【发布时间】:2020-05-06 18:26:30
【问题描述】:
我正在尝试在 fetch 或 axios 上设置 cookie,我已经检查了发布在 github 或 stackoverflow 上的解决方案,但它们现在都没有工作。 我正在使用 Saml 对我的 RN 项目进行身份验证。
所以这里有故事:
第一次登录时,如果用户点击开始按钮,则调用get profile info的api,如果header没有cookie,则返回redirect url和cookie(它是unauth cookie),然后转到webview上的url,用户登录webview后,在webview上调用原始url(get profile api),之后,我会使用react-native-cookies库获取auth cookie,然后将其设置为fetch/axios 的头文件。但它不起作用。
export async function getMyProfile() {
const cookies = await LocalStorage.getAuthCookies();
await CookieManager.clearAll(true)
const url = `${Config.API_URL}/profiles/authme`;
let options = {
method: 'GET',
url: url,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true
};
if (cookies) options.headers.Cookie = cookies.join(';')
return axios(options)
.then(res => {
console.info('res', res);
return res;
}).catch(async (err) => {
if (err.response) {
if (err.response.status === 401) {
const location = _.get(err, 'response.headers.location', null);
const cookie = _.get(err, 'response.headers.set-cookie[0]', null);
await LocalStorage.saveUnAuthCookie(cookie);
return { location, cookie, isRedirect: true };
}
}
});
}
【问题讨论】:
-
你是如何在 react-native 中使用 LocalStorage 的?
-
登录 webview 后,我会将 cookie 存储在本地存储中。从 LocalStorage 存储/获取正常工作。
标签: react-native axios fetch saml