[英]How to set cookie in React Native with Expo?
我很難讓 cookie 工作,在服務器端,我使用它們通過從 req.cookies 中獲取它們來驗證用戶。
這是我目前在 React Native 中的 Login.js 文件中設置它的方式:
import Cookies from "universal-cookie";
const cookies = new Cookies();
cookies.set("token", token, {
expires: 7, // 7 days
path: "/"
//,secure: true // If served over HTTPS
});
當我在此頁面上調用cookies.get("token")
時,這工作正常。 但是,當我導入、設置常量並在另一個頁面上調用 get 時,令牌沒有顯示......
另外,當我像這樣進行提取時:
fetch("http://192.168.0.115:3000/myTransactions/", {
credentials: "same-origin",
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
服務器不會收到任何 cookie。 我什至更改了憑據以說包含。
我在 Windows 上使用 expo 和我的終端來運行它,而無需使用 android studio 或 xcode。 我不確定這是否是一個可能的問題。
有什么想法嗎!
謝謝
有幾件事... react-native-keychain ... 比 cookie 更安全! https://github.com/oblador/react-native-keychain
其次,您是否嘗試過 AsyncStorage? 這本質上是內置在“localStorage”中的 React-native。 我想這就是你要找的。
https://facebook.github.io/react-native/docs/asyncstorage.html
// to set
AsyncStorage.setItem('@app:session', token);
// to get
AsyncStorage.getItem('@app:session').then(token => {
// use token
});
OP 的更新如果您的設置看起來像這樣,您只是將令牌值作為標頭發送,您可以以任何格式存儲此信息......最安全/最方便。 在這個例子中, auth 可以是這些選項中的任何一個獲取......
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;
});
};
您可以使用 cookie 或僅將令牌存儲在 web 應用程序的localStorage中。
但是對於 React Native 應用程序,使用AsyncStorage將是更好的解決方案。
關於異步存儲:
AsyncStorage 是一個簡單的、未加密的、異步的、持久的、鍵值存儲系統,對應用程序是全局的。 應該使用它代替 LocalStorage。
在 iOS 上,AsyncStorage 由本機代碼支持,該代碼將小值存儲在序列化字典中,並將較大值存儲在單獨的文件中。 在 Android 上,AsyncStorage 將根據可用內容使用 RocksDB 或 SQLite。
此外,AsyncStorage 有非常簡單的 API:
const TOKEN = "TOKEN";
// save token
AsyncStorage.setItem(TOKEN, token);
// get token
AsyncStorage.getItem(TOKEN).then(token => {
// token value could be used
});
如果您擔心AsyncStorage安全性,您可以通過鏈接找到更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.