如何使用Expo在React Native中设置cookie?

问题描述 投票:3回答:2

我很难让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")时,这很好用。但是,当我导入时,设置const,并在另一个页面上调用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。我不确定这是否是一个可能的问题。

有什么想法吗!

谢谢

javascript reactjs cookies react-native
2个回答
2
投票

几件事......反应原生钥匙链......比饼干更安全! https://github.com/oblador/react-native-keychain

其次,你试过AsyncStorage吗?这本质上是在“localStorage”中构建的React-natives。我认为这就是你要找的东西。

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;
    });
};

0
投票

您可以使用cookie或仅在web应用程序的localStorage中存储令牌。

但对于React Native应用程序,AsyncStorage的使用将是更好的解决方案。

关于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安全性感到烦恼,可以通过link找到更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.