How can I set a cookie in react?

最初,我使用以下 ajax 来设置 cookie。

function setCookieAjax(){
$.ajax({
url: `${Web_Servlet}/setCookie`,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
headers: { 'Access-Control-Allow-Origin': '*',
'username': getCookie("username"),
'session': getCookie("session")
},
type: 'GET',
success: function(response){
setCookie("username", response.name, 30);
setCookie("session", response.session, 30);}
})
}


function setCookie(cname, cvalue, minutes) {
var d = new Date();
d.setTime(d.getTime() + (minutes*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}


export const getUserName = (component) => {
setCookieAjax()
$.ajax({
url: `${Web_Servlet}/displayHeaderUserName`,
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
headers: { 'Access-Control-Allow-Origin': '*',
'username': getCookie("username"),
'session': getCookie("session")
},
type: 'GET',
success: function(response){
component.setState({
usernameDisplay: response.message
})
}.bind(component)
})
}

现在,我想使用 servlet 的添加 cookie 函数来设置 cookie。但我不知道如何实现我的目标。

Cookie loginCookie = new Cookie("user",user);  //setting cookie to expiry in 30 mins
loginCookie.setMaxAge(30*60);
loginCookie.setDomain("localhost:4480");
loginCookie.setPath("/");


response.addCookie(loginCookie);

为了扩展 Cookie 的时间限制,我应该在响应端写些什么来接收 Cookie 的会话时间?

388430 次浏览

我在 React 中使用 response-cookie 库设置 Cookie,它有一些选项,您可以传递这些选项来设置过期时间。

看看 给你

举个例子来说明你的情况:

import cookie from "react-cookie";


setCookie() => {
let d = new Date();
d.setTime(d.getTime() + (minutes*60*1000));


cookie.set("onboarded", true, {path: "/", expires: d});
};

看起来 react-cookie npm 包中以前提供的功能已经移到了 universal-cookie中。现在 通用 cookie 存储库的相关例子是:

import Cookies from 'universal-cookie';
const cookies = new Cookies();
cookies.set('myCat', 'Pacman', { path: '/' });
console.log(cookies.get('myCat')); // Pacman

一个非常简单的解决方案是使用 sfcookies 包。 您只需要使用 npm 安装它,例如: Npm 安装 sfcookies ——保存

然后在文件中导入:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

创建 cookie 密钥:

const cookie_key = 'namedOFCookie';

在你的提交函数中,你通过保存数据来创建 cookie,就像这样:

bake_cookie(cookie_key, 'test');

删掉就删掉吧

delete_cookie(cookie_key);

并且阅读它:

read_cookie(cookie_key)

简单易用。

默认情况下,当 fetch网址时,React 本机设置 cookie。

查看 cookies 并确保可以使用 https://www.npmjs.com/package/react-native-cookie包。 I used to be very satisfied with it.

当然,如果提供了 去捡 证件配置,就会这样做

credentials: "include", // or "same-origin" or "omit"

但是如何使用它

——在安装这个软件包之后——

去买饼干:

import Cookie from 'react-native-cookie';


Cookie.get('url').then((cookie) => {
console.log(cookie);
});

设置饼干:

Cookie.set('url', 'name of cookies', 'value  of cookies');

only this

但是如果你想要一些,你可以做到这一点

1-嵌套:

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
.then(() => {
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
.then(() => {
...
})
})

第二,重归于好

Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
....

现在,如果你想确保饼干已经设置好了,你可以重新设置以确保。

Cookie.get('url').then((cookie) => {
console.log(cookie);
});

例如,使用香草 js

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

阅读更多: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

您可以使用默认的 javascript Cookie 集方法。

createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
let date = new Date();
date.setTime(date.getTime()+(hourToExpire*60*60*1000));
document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},

调用反应方法中的 java 脚本函数,

createCookieInHour('cookieName', 'cookieValue', 5);

你可以使用下面的方式来查看 cookie。

let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);

详情请参阅以下文件 -网址

Little update. There is a hook available for react-cookie

1)首先,安装依赖项(仅供参考)

yarn add react-cookie

or

npm install react-cookie

2)我的用法例子:

// SignInComponent.js
import { useCookies } from 'react-cookie'


const SignInComponent = () => {


// ...


const [cookies, setCookie] = useCookies(['access_token', 'refresh_token'])


async function onSubmit(values) {
const response = await getOauthResponse(values);


let expires = new Date()
expires.setTime(expires.getTime() + (response.data.expires_in * 1000))
setCookie('access_token', response.data.access_token, { path: '/',  expires})
setCookie('refresh_token', response.data.refresh_token, {path: '/', expires})


// ...
}


// next goes my sign-in form


}

Hope it is helpful.

对于上面例子的改进建议非常感谢!

使用 Js-cookie 包

npm i js-cookie

import Cookies from 'js-cookie'


Cookies.set('auth', 'data')
Cookies.get('auth')

这个 npm 包工作为我和远远好

只需使用 react-cookie库:

npm install react-cookie

索引:

import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";
import App from "./App";


const rootElement = document.getElementById("root");
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
rootElement
);

USAGE:

反应挂钩:

import React from "react";
import { useCookies } from "react-cookie";


export default function App() {
const [cookies, setCookie] = useCookies(["user"]);


function handleCookie() {
setCookie("user", "gowtham", {
path: "/"
});
}
return (
<div className="App">
<h1>React cookies</h1>
<button onClick={handleCookie}>Set Cookie</button>
</div>
);
}

class-based组件:

import React, { Component } from "react";
import { instanceOf } from "prop-types";
import { withCookies, Cookies } from "react-cookie";


class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};


state = {
user: this.props.cookies.get("user") || ""
};


handleCookie = () => {
const { cookies } = this.props;
cookies.set("user", "gowtham", { path: "/" }); // setting the cookie
this.setState({ user: cookies.get("user") });
};


render() {
const { user } = this.state;
return (
<div className="App">
<h1>React cookies</h1>
{user && <p>{user}</p>}
<button onClick={this.handleCookie}>Set Cookie</button>
</div>
);
}
}


export default withCookies(App);

Document 属性 Cookie 允许读写与文档关联的 Cookie。它充当 Cookie 实际值的 getter 和 setter。

document.cookie = "doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=None; Secure";

Know more