Lio*_*789 6 javascript cookies reactjs react-native
我很难让 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
});
Run Code Online (Sandbox Code Playgroud)
当我cookies.get("token")在此页面上调用 a 时,这工作正常。但是,当我导入、设置常量并在另一个页面上调用 get 时,令牌没有显示......
另外,当我像这样进行提取时:
fetch("http://192.168.0.115:3000/myTransactions/", {
credentials: "same-origin",
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
Run Code Online (Sandbox Code Playgroud)
服务器不会收到任何 cookie。我什至更改了凭据以说包含。
我在 Windows 上使用 expo 和我的终端来运行它,而无需使用 android studio 或 xcode。我不确定这是否是一个可能的问题。
有什么想法吗!
谢谢
react-native-keychain比 cookies 更安全!
其次,您尝试过AsyncStorage吗?这本质上是 React Native 内置的“localStorage”。我想这就是你要找的。
// to set
AsyncStorage.setItem('@app:session', token);
// to get
AsyncStorage.getItem('@app:session').then(token => {
// use token
});
Run Code Online (Sandbox Code Playgroud)
如果您的设置如下所示,您只需将令牌值作为标头发送,则可以以最安全/最方便的任何格式存储此信息。
在此示例中,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;
});
};
Run Code Online (Sandbox Code Playgroud)