NodeJS 如何删除Cookie会话?

2mbi3lxu  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(116)

这是我的代码:

var express = require('express')
var sessionCookie = require('cookie-session')
var app = express();

app.use(sessionCookie({ keys: ['abc'], name: 'user' }));

app.get('/', function (req, res, next) {
  req.session.views = (req.session.views || 0) + 1;
  res.end(JSON.stringify(req.session));
  console.log('req.session', req.session);
});

app.get('/logout', (req, res) => {
  req.session = {};
  // req.session = null;
  console.log("req.session(logOut): ", req.session);
  res.redirect('/');
});

app.listen(3000);

为什么我使用req.session = {}时会话没有被删除,但当我使用req.session = null时会话被删除。

disbfnqx

disbfnqx1#

查看源代码v2.0.0/index.js#L124
req.session有一个setter/getter函数,参见:

// define req.session getter / setter
Object.defineProperty(req, 'session', {
  configurable: true,
  enumerable: true,
  get: getSession,
  set: setSession
})

当您将req.session设置为null时,sess变量将被设置为false。如果将一个空对象{}设置为req.session,如您所见,它将创建一个新会话。

function setSession (val) {
  if (val == null) {
    // unset session
    sess = false
    return val
  }

  if (typeof val === 'object') {
    // create a new session
    sess = Session.create(val)
    return sess
  }

  throw new Error('req.session can only be set as null or an object.')
}

最后,cookie-session将使用on-headers包来设置cookie,如果sessfalse,则cookie将被设置为''

onHeaders(res, function setHeaders () {
  if (sess === undefined) {
    // not accessed
    return
  }

  try {
    if (sess === false) {
      // remove
      debug('remove %s', name)
      cookies.set(name, '', req.sessionOptions) // <- here
    } else if ((!sess.isNew || sess.isPopulated) && sess.isChanged) {
      // save populated or non-new changed session
      debug('save %s', name)
      cookies.set(name, Session.serialize(sess), req.sessionOptions)
    }
  } catch (e) {
    debug('error saving session %s', e.message)
  }
})

相关问题