我正在尝试在fetch或axios上设置cookie,我已经检查了github或stackoverflow上发布的解决方案,但他们现在都没有工作。
所以这里是故事。
在第一次登录时,如果用户点击开始按钮,它会调用get profile info的api,如果头顶没有cookie,它会返回重定向url和cookie(这是unuth cookie),并转到webview上的url,当用户在webview上登录后,然后在webview上调用原来的url(get profile api),之后,我会使用react-native-cookies库抓取auth cookie,然后在fetchaxios的头顶设置它。但这并不奏效。
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 };
}
}
});
}
你可以使用Axios拦截器。
let cookie = null;
const axiosObj = axios.create({
baseURL: '',
headers: {
'Content-Type': 'application/json',
},
responseType: 'json',
withCredentials: true, // enable use of cookies outside web browser
});
// this will check if cookies are there for every request and send request
axiosObj.interceptors.request.use(async config => {
cookie = await AsyncStorage.getItem('cookie');
if (cookie) {
config.headers.Cookie = cookie;
}
return config;
});