express cookie session 使用

1、安装

npm install --save express
npm install --save cookie-parser cookie-session

2、cookie

const app = express();
// 添加 cookie-parser 中间件  'secret'(签名的密钥)
app.use(cookieParser('secret'));

app.get('/', (req, res) => {
  res.cookie('a', 1);
  res.cookie('b', 2, {signed: true}); // 添加签名
  res.end('ok');
});

app.get('/getCookie', (req, res) => {
  res.json({
    cookie: req.cookies,
    signedCookies: req.signedCookies // 签名后的cookie
  });
});

// {"cookie":{"a":"1"},"signedCookies":{"b":"2"}}

3、session

const app = express();
app.use(cookieParser('secret'));
app.use(cookieSession({
  name: 'sess', // cookie 名
  keys: ['aaa', 'bbb', 'ccc'], // 每次请求会循环取一个数值进行加密
  maxAge: 1000*60*60
}));

app.get('/', (req, res) => {
  if (req.session['count'] == null) {
    req.session['count'] = 1
  } else {
    req.session['count'] ++;
  }
  console.log(req.session['count']);
  res.end('ok');
});

app.get('/getCookie', (req, res) => {
  const r = {
    count: {
      cookie: req.cookies,
      signedCookies: req.signedCookies,
      session: req.session['count']
    }
  }
  res.json(r);
});

你可能感兴趣的:(express cookie session 使用)