问题
In all prev versions of Expo, I used RN fetch method to POST username/password to a Flask login endpoint. This endpoint saved user info to the session and set session cookie. It was always transparent and I never had to pass anything extra.
This worked as of Expo v28. But when I upgraded to Expo 30, the server no longer sees the client as logged in. Do I need to change how I use fetch? Do I need to pass some extra parameters?
回答1:
First, before login, we need to clear the old cookies using:
import { NativeModules } from 'react-native'
const Networking = NativeModules.Networking;
Networking.clearCookies((cleared) => {
console.debug('cleared hadCookies: ' + cleared.toString());
ApiUtils.login(your_login_parameters); // your login function
});
We have to clear the cookies because the native cookie manager is sending stale cookies. Now, we will manage the cookie ourselves.
In my login handler, I use set-cookie-parser to parse the cookies sent by the server in the 'set-cookie' response header.
import setCookie from 'set-cookie-parser';
// insider my login handler
const response = await fetch(login_endpoint, credentials_payload);
let cookies, cookieHeader, serverData;
if (response.ok) {
serverData = await response.json();
cookieHeader = setCookie.splitCookiesString(response.headers.get('set-cookie'));
cookies = setCookie.parse(cookieHeader);
console.log(cookies); // array
// Save cookies array to SecureStore or AsyncStorage
}
Finally, for all requests to the server that require session cookie, we send the cookie in the fetch headers.
const makeFetchParams = (form_data) => {
const cookies = get_from_storage_of_choice // SecureStore or AsyncStorage
const c_arr = cookies.map(d => { return d.name+'='+d.value; });
const cookieStr = c_arr.join(';');
return {
method: 'POST',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'cookie': cookieStr
},
body: form_data
};
};
// inside endpoints that require the session cookie
const response = await fetch(your_url, makeFetchParams(some_form_data));
I tested this with Expo SDK v30 and Android. This is works-for-me solution may be of use to others.
来源:https://stackoverflow.com/questions/53111431/expo-sdk-29-30-session-cookie-from-login