简体   繁体   English

如何使用节点 cookie-session 创建 cookie

[英]How to create a cookie with node cookie-session

I am running a small node app.我正在运行一个小型节点应用程序。 And I am trying to get it to create a cookie for each visitor, called 'session' that contains - for example - the session id.我试图让它为每个访问者创建一个 cookie,称为“会话”,其中包含 - 例如 - session id。 But I cannot seem to get node to create a cookie through cookie-session.但我似乎无法让节点通过 cookie-session 创建 cookie。 My code so far:到目前为止我的代码:

const fs = require('fs');
const http = require('http');
const https = require('https');
const privateKey = fs.readFileSync('PATHTOKEY');
const certificate = fs.readFileSync('PATHTOKEY');
const credentials = {key: privateKey, cert: certificate};
const Keygrip = require("keygrip");    

const express = require('express');
const app = express();    

const port = APORTNUMBER;
const secureport = APORTNUMBER;
const helmet = require('helmet');    

const options = {
  dotfiles: 'deny',
  etag: true,
  extensions: ['html', 'htm'],
  index: 'index.html',
  lastModified: true,
  maxAge: 0,
  redirect: true,
  setHeaders: function (res, path, stat) {
    res.set('x-timestamp', Date.now())
  }
};    

app.use(express.static('public', options), helmet());    

So far, no problems.到目前为止,没有任何问题。 But then comes the middleware cookie-session.但随后出现了中间件 cookie 会话。

const session = require('cookie-session');
const expiryDate = new Date(Date.now() + 60 * 60 * 1000); // 1 hour    

app.use( 
  session({
    name: 'session',
    keys: new Keygrip(["MYSECRET1", "MYSECRET2"]),
    cookie: {
      secure: true,
      httpOnly: true,
      expires: expiryDate
    }
  })
);    

Above, I've specified the middleware to use these cookie-session parameters, but how do I proceed from here to actually get it to create this cookie?上面,我已经指定了中间件来使用这些 cookie-session 参数,但是我如何从这里开始实际获取它来创建这个 cookie?

const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);    

httpServer.listen(port);
httpsServer.listen(secureport);    

console.log("Node server started");

Your current code looks right, based also on the documentation @ http://expressjs.com/en/resources/middleware/cookie-session.html您当前的代码看起来正确,也基于文档@ http://expressjs.com/en/resources/middleware/cookie-session.html

I would suggest defining an app.get and testing everything with a tool like postman or fidler.我建议定义一个app.get并使用 postman 或提琴手之类的工具测试所有内容。

eg例如

app.get('/test', function (req, res, next) {
  // Update views
  req.session.views = (req.session.views || 0) + 1

  // Write response
  res.end(req.session.views + ' views')
})

I've not been able to figure out how to work with neither express-cookie nor cookie-session.我无法弄清楚如何使用 express-cookie 和 cookie-session。 However, I have been able to create cookies with cookie-parser middleware.但是,我已经能够使用 cookie-parser 中间件创建 cookies。

dependency:依赖:

const cookieParser = require('cookie-parser');

config:配置:

const cookieConfig = {
  httpOnly: true,
  secure: true,
  maxAge: 1800,
  signed: true
};

Express:表达:

app.use(cookieParser('MYSECRET'));    

app.use(function (req, res, next) {
  let cookie = req.cookies.cookieName;
  if (cookie === undefined) {
    let randomNumber=LOGICFORRANDOMNUMBER
    res.cookie('COOKIENAME', randomNumber, cookieConfig);
  };
  next();
});

Well, after trying this myself I manages to successfully use the cookie-session middleware.好吧,在我自己尝试之后,我成功地使用了cookie-session中间件。 yay

I'm using the middleware like this:我正在使用这样的中间件:

app.use(cookieSession({
  name: 'session', // replace this with your own name to suit your needs
  keys: [ 'your-secret-key-goes-here', null ]
})

About the null value in keys option - the docs and related examples always use 2 keys, despite the TypeScript @types lib declares that关于keys选项中的null值 - 文档和相关示例始终使用 2 个键,尽管 TypeScript @types lib 声明

The list of keys to use to sign & verify cookie values.用于签署和验证 cookie 值的密钥列表。 Set cookies are always signed with keys[0], while the other keys are valid for verification, allowing for key rotation.设置 cookies 始终使用 keys[0] 签名,而其他密钥对验证有效,允许密钥轮换。

So.. I've used only one key and it works as excepted所以..我只使用了一个键,它的工作原理是例外

Note that I'm using this middleware before I'm registering the express app routes in order for this middleware to take effect before the router is executed (per request)请注意,我在注册快速app路由之前使用此中间件,以便此中间件在路由器执行之前生效(每个请求)

In each of my routes I can use the middleware using something like this在我的每条路线中,我都可以使用类似这样的中间件

app.get('/test', (req, res) => {
  req.session.test = { a: 5, b: 7} // yes - JSON payload are valid :)
})

To verify - ensure that your initial request got the following headers验证 - 确保您的初始请求具有以下标头

Set-Cookie: session=eyJ0ZXN0Ijp7ImEiOjUsImIiOjd9fQ==; path=/; secure; httponly
Set-Cookie: session.sig=D4VVF4XSbBEWXI4b04ZvybAxppw; path=/; secure; httponly

This is only an example where the session is the name of the cookie as I've defined earlier.这只是一个示例,其中session是我之前定义的 cookie 的名称。 Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM