connect.cookieParser and connect.session

2019-06-07 00:17发布

问题:

I am new to connect framework. I want to use cookieParser() and session management. Please correct the below code and why it shown this error.

var connect = require("connect");
var app = connect();
connect()
    .use(connect.cookieParser())
    .use(connect.session({ secret: 'some secret text', cookie: { maxAge:       30000}}))
    .use(function(req, res) {
        var sess = req.session,
        url = req.url.split("/");

    if (url[1] == "name" && url[2]) {
        sess.name = url[2];
        res.end("name saved: " + url[2]);
    } else if (sess.name) {
        res.write("session-stored name: " + sess.name);    
        res.end("stored for another: " + (sess.cookie.maxAge / 1000) +seconds");
    } else {
        res.end("no stored name; go to /name/{name} to save a name");
    }
}).listen(3000);

Following is error shown:

C:\Users\Sagar\workspace\Node_connect\public\session.js:5
    .use(connect.cookieParser())
                 ^
TypeError: undefined is not a function
    at Object.<anonymous> (C:\Users\Sagar\workspace\Node_connect\public\session.js:5:18)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

回答1:

Since version 2.21.0 (2014-06-20) of Connect they deprecated cookie-parser integration (https://github.com/senchalabs/connect/blob/master/History.md) and you should install it separately:

npm install cookie-parser --save

Then use it like shown below:

var connect = require('connect'),
        cookieParser = require('cookie-parser');
var app = connect()
    .use(cookieParser())
    .use(...)
...


回答2:

var express = require('express') var cookieParser = require('cookie-parser')

var app = express() app.use(cookieParser())

reference: https://www.npmjs.com/package/cookie-parser