反应本地获取Cookie [英] react native get cookies

查看:31
本文介绍了反应本地获取Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用fetch()登录到服务器,我想知道如何获取cookie.

I had logined in my server with fetch(),I want to know how I get the cookies.

我知道我可以在Web浏览器开发中使用" document.cookie "来获取cookie,但是在响应本机开发中该如何做?非常感谢.

I know that I can use "document.cookie" to get the cookies in a web browser development,but in react native develop how? thank you very much.

推荐答案

我刚刚遇到了同样的问题.我的第一种方法是从响应头中手动获取cookie.由于 Headers.prototype.getAll 被删除,这变得更加困难(请参阅此问题).详细信息在下面进一步显示.

I just came across the same problem. My first approach was to manually get the cookies from the response headers. This become more difficult since Headers.prototype.getAll was removed (see this issue). The details are shown further down below.

首先,我想提一下以下所有cookie解析都是不必要的,因为在 React Native 上实现 fetch 会自动发送cookie(如果 credentials 键设置正确).因此,保留了会话(就像在浏览器中一样),并且进一步的 fetch es可以正常工作.不幸的是, Networking 上的React Native文档没有明确告诉您它将立即可用.它只说:"React Native提供了Fetch API来满足您的网络需求."

First, I want to mention that all the below cookie parsing turned out to be unnecessary because the implementation of fetch on React Native sends the cookies automatically (if the credentials key is set correctly). So the session is kept (just like in the browser) and further fetches will work just fine. Unfortunately, the React Native documentation on Networking does not explicitly tell you that it'll work out of the box. It only says: "React Native provides the Fetch API for your networking needs."

因此,我编写了一个辅助函数:

Thus, I wrote a helper function:

// 'headers' is iterable
const get_set_cookies = function(headers) {
    const set_cookies = []
    for (const [name, value] of headers) {
        if (name === "set-cookie") {
            set_cookies.push(value)
        }
    }
    return set_cookies
}

fetch(url, {
    method: "POST",
    credentials: "same-origin", // or 'include' depending on CORS
    // ...
})
.then(response => {
    const set_cookies = get_set_cookies(response.headers)
})

要将Cookie字符串解析为对象,我使用了 set-cookie-parser .这样,我想像这样手动将cookie发送回去

To parse the cookie strings into objects I used set-cookie-parser. This way I wanted send the cookies back manually like

import SetCookieParser from "set-cookie-parser"

const cookies_to_send = set_cookies
    .map(cookie => {
        const parsed_cookie = SetCookieParser.parse(cookie)
        return `${cookie.name}=${cookie.value}`
    })
    .join('; ')

fetch(url, {
    method: "POST",
    credentials: "same-origin", // or 'include' depending on CORS
    headers: {
        Cookie: cookies_to_send,
        // ...
    },
    // ...
})

这篇关于反应本地获取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆