Express.js 中的 res.cookie() 方法


**res.cookie()** 方法用于将 cookie 名称设置为值。value 参数可以是字符串或转换为 JSON 的对象。

语法

res.cookie( name, value, [options] )

参数

options 参数可以具有以下值:

  • **domain** - 表示 cookie 的域名。默认指的是应用程序的域名。

  • **encode** - 此参数用于在异步函数中对 cookie 值进行编码。

  • **expires** - 此参数以 GMT 格式定义 cookie 的过期时间。默认值为 0,这将创建一个会话 cookie。

  • **httpOnly** - 此布尔参数将 cookie 标记为仅供 Web 服务器使用。

  • **maxAge** - 此参数表示一个方便的选项,用于以毫秒为单位设置相对于当前时间的过期时间。

  • **path** - 这是存储 cookie 的路径。默认值为“/”。

  • **secure** - 这将 cookie 标记为仅与 https 一起使用。

  • **signed** - 这指示 cookie 是否应该被签名。

示例

创建一个名为“resCookie.js”的文件并复制以下代码片段。创建文件后,使用命令“node resCookie.js”运行此代码,如以下示例所示:

// res.cookie(name, value, [options]) Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function(req, res){
   // Setting the below key-value pair
   res.cookie('name', 'tutorialsPoint');
   res.send("Cookies are set");
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

使用 GET 请求访问以下端点:**https://:3000/api**。

输出

C:\home
ode>> node resCookie.js Server listening on PORT 3000 Cookies are set

更新于: 2022-01-29

7K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.