I am having a hard time getting cookies to work, on the server side I use them to verify the user by grabbing them from req.cookies.
Here is how I currently set it on the Login.js file in React Native:
import Cookies from "universal-cookie";
const cookies = new Cookies();
cookies.set("token", token, {
expires: 7, // 7 days
path: "/"
//,secure: true // If served over HTTPS
});
This works fine when I call a cookies.get("token")
on this page. However, when I import, setup the const, and call get on another page the token does not show up...
Also, when I make the fetch like this:
fetch("http://192.168.0.115:3000/myTransactions/", {
credentials: "same-origin",
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
The server does not receive any cookies. I even changed credentials to say include.
I am using expo and my terminal on Windows to run it without having to use android studio or xcode. I am not sure if that is a possible issue.
Any thoughts!
Thanks
Here is how I currently set it on the Login. js file in React Native: import Cookies from "universal-cookie"; const cookies = new Cookies(); cookies. set("token", token, { expires: 7, // 7 days path: "/" //,secure: true // If served over HTTPS });
Note: this post was originally published on February 28, 2019, and subsequently updated on March 14, 2019 to reflect improvements to the workflow. Starting today, you can use as little or as much of the Expo SDK as you like in any React Native app.
React Native relies on the native (Android and iOS) APIs written in Java and Objective-C. You may think the cookie usage is as straightforward as using it within the browser but unfortunately, it isn't.
react-native-keychain is safer than cookies!
Second, have you tried AsyncStorage? This is React Native built in "localStorage" in essence. I think it's what you're looking for.
// to set
AsyncStorage.setItem('@app:session', token);
// to get
AsyncStorage.getItem('@app:session').then(token => {
// use token
});
If your setup looks like this, where you simply are sending the token value through as headers, you can store this information in whatever format is safest/most convenient.
In this example, auth could be either of these options fetched.
localStorage.set('token', 38573875ihdkhai)
createCookie('ppkcookie' 7asdfasdf);
export const userFetchRequest = () => (dispatch, getState) => {
let {auth} = getState();
return superagent.get(`${__API_URL__}/user/me`)
.set('Authorization', `Bearer ${auth}`)
.then(res => {
dispatch(userSet(res.body));
return res;
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With