繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM