Node.js and express - how to read a cookie but is undefined

前端 未结 3 416
灰色年华
灰色年华 2020-12-29 06:47

I use the below to set a cookie using express.

res.cookie(\'test\', \'yes\', { 
    expires: new Date(Date.now() + 365*2*24*60*60*1000), 
    httpOnly: true          


        
相关标签:
3条回答
  • 2020-12-29 07:01

    I solved it by adding app.use(express.cookieParser()); above the app.router.

    0 讨论(0)
  • 2020-12-29 07:11

    You need to use express.cookieParser() before app.router; middleware is run in order, meaning it's never even reaching cookieParser() before your route is executed.

    Try this:

      app.set('views', __dirname + '/views');
      app.set('view engine', 'jade');
      app.use(express.bodyParser());
      app.use(express.methodOverride());
      app.use(express.cookieParser());
      app.use(app.router);
      app.use(express.static(__dirname + '/public'));
    
    0 讨论(0)
  • 2020-12-29 07:17

    Most middleware (like cookieParser) is no longer bundled with Express and must be installed separately.

    Install cookie-parser:

    npm install cookie-parser
    

    Usage

    var express      = require('express')
    var cookieParser = require('cookie-parser')
    
    var app = express()
    app.use(cookieParser())
    

    https://github.com/expressjs/cookie-parser

    0 讨论(0)
提交回复
热议问题