connect.cookieParser and connect.session

2019-06-07 00:07发布

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

2条回答
等我变得足够好
2楼-- · 2019-06-07 00:48

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

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

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

查看更多
仙女界的扛把子
3楼-- · 2019-06-07 00:54

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(...)
...
查看更多
登录 后发表回答