在我的应用程序中,我需要使用快捷框架设置一个cookie。我已经尝试了下面的代码,但它没有设置cookie。

var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
      app.use(express.cookieParser());
      app.use(express.static(__dirname + '/public'));

      app.use(function (req, res) {
           var randomNumber=Math.random().toString();
           randomNumber=randomNumber.substring(2,randomNumber.length);
           res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })

           console.log('cookie have created successfully');
      });

});

var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);

当前回答

同构读cookie助手:

function getCookieValue(cookieName = '', cookie = '') {
  const matches = cookie.match(`(^|[^;]+)\\s*${cookieName}\\s*=\\s*([^;]+)`)
  return matches ? matches.pop() : ''
}

// Node with express:
getCookieValue('cookieName', req.headers.cookie)

// Browser:
getCookieValue('cookieName', document.cookie)

用express写入节点:

res.cookie('cookieName', 'cookieValue')

在浏览器中编写:

function setCookie(
  cname,
  cvalue,
  exdays = 100 * 365 /* 100 days */
) {
  const now = new Date()
  const expireMs = exdays * 24 * 60 * 60 * 1000
  now.setTime(now.getTime() + expireMs)

  document.cookie = `${cname}=${cvalue};expires=${now.toUTCString()};path=/`
}

// Example of usage
setCookie('cookieName', 'cookieValue')

其他回答

在Express中使用中间件的顺序很重要:前面声明的中间件将首先被调用,如果它可以处理请求,后面声明的任何中间件都不会被调用。

如果表达。Static正在处理请求,你需要移动你的中间件:

// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());

// set a cookie
app.use(function (req, res, next) {
  // check if client sent cookie
  var cookie = req.cookies.cookieName;
  if (cookie === undefined) {
    // no: set a new cookie
    var randomNumber=Math.random().toString();
    randomNumber=randomNumber.substring(2,randomNumber.length);
    res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
    console.log('cookie created successfully');
  } else {
    // yes, cookie was already present 
    console.log('cookie exists', cookie);
  } 
  next(); // <-- important!
});

// let static middleware do its job
app.use(express.static(__dirname + '/public'));

同样,中间件需要结束请求(通过发回响应),或者将请求传递给下一个中间件。在本例中,我通过在设置cookie时调用next()来实现后一种方法。

更新

到目前为止,cookie解析器是一个单独的npm包,所以不用

app.use(express.cookieParser());

你需要使用NPM I cookie-parser单独安装它,然后将其用作:

const cookieParser = require('cookie-parser');
app.use(cookieParser());

饼干?

res.cookie('cookieName', 'cookieValue')

读过饼干吗?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})

同构读cookie助手:

function getCookieValue(cookieName = '', cookie = '') {
  const matches = cookie.match(`(^|[^;]+)\\s*${cookieName}\\s*=\\s*([^;]+)`)
  return matches ? matches.pop() : ''
}

// Node with express:
getCookieValue('cookieName', req.headers.cookie)

// Browser:
getCookieValue('cookieName', document.cookie)

用express写入节点:

res.cookie('cookieName', 'cookieValue')

在浏览器中编写:

function setCookie(
  cname,
  cvalue,
  exdays = 100 * 365 /* 100 days */
) {
  const now = new Date()
  const expireMs = exdays * 24 * 60 * 60 * 1000
  now.setTime(now.getTime() + expireMs)

  document.cookie = `${cname}=${cvalue};expires=${now.toUTCString()};path=/`
}

// Example of usage
setCookie('cookieName', 'cookieValue')

如果您在为一个请求设置多个cookie时有问题

试试这个方法:

res.setHeader('Set-Cookie', [
    `accessToken=${accessToken}; HttpOnly; Path=/; Max-Age=${60 * 60}; Secure=True;`,
    `refreshToken=${refreshToken}; HttpOnly; Path=/; Max-Age=${60 * 60 * 24 * 7 * 2}; Secure=True;`
]);

设置cookie可以这样做: Res.cookie ('cookie名称','cookie值',[options])

其中cookie_name是您希望设置的cookie的名称(字符串),例如-“token”,cookie值是您希望存储在该cookie中的值(字符串)。 至于选项,你可以在这里阅读更多: https://expressjs.com/en/api.html

选项的一个例子是“maxAge”,它指示cookie的有效期,例如在分配认证令牌时使用,并且您希望限制用户在重新登录之前可以保持登录的时间。

读取cookie可以这样做: 要求的事情。饼干(“饼干的名字”)

它将返回cookie的值。