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.
Now, inside your React component, you can access the cookie by using a useCookies() hook. The cookies object is holding the all cookies, you have created in your app. In class-based components, you can get the cookie by using a withCookies() higher-order component.
React Native has its own cookie management, meaning that when the server returns header Set-Cookie, the next API call will already have that cookie set on its header by default, so providing the cookie here will have to effect.
The Solution after successful login, the server responds with the status and cookies. cookies are saved on the device (Async Storage)
js file in React Native: import Cookies from "universal-cookie"; const cookies = new Cookies(); cookies. set("token", token, { expires: 7, // 7 days path: "/" //,secure: true // If served over HTTPS }); This works fine when I call a cookies.
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.
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 fetch
es 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)
})
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,
// ...
},
// ...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With