react native get cookies

一个人想着一个人 提交于 2021-02-04 17:21:11

问题


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

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.


回答1:


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.

Getting and parsing cookies might be unnecessary

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."

First approach

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

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,
        // ...
    },
    // ...
})



回答2:


Inspired by jneuendorf, I created a helper method that returns a key/value pair to easily look up the value of a cookie

export const getCookies = function(response) {
  const cookies = {}
  for (const [name, values] of response.headers) {
    if (name === 'set-cookie') {
      for (const cookie of values.split(';')) {
        const [key, value] = cookie.split('=')
        cookies[key] = value
      }
    }
  }

  return cookies
}


来源:https://stackoverflow.com/questions/39159138/react-native-get-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!