Express:无法同时访问POST数据和设置cookie

时间:2013-04-26 14:39:20

标签: node.js cookies express

我正在编写一个接收帖子请求的应用程序,并设置从POST信息中提取的cookie。我陷入困境22.在第一个代码示例中,我可以设置cookie但无法访问数据,在第二个我可以访问数据但无法设置cookie。我确定我错过了一些关于中间件如何工作的基本概念,但我不能为我的生活找到我需要的信息。

下面的代码按预期创建cookie,但我的post变量未定义

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , handshake = require('./routes/handshake')
  , http = require('http')
  , path = require('path');

var app = express();   
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride()); 
app.use(function (req, res, next) {
    var cookie = req.cookies.cokkieName;
    console.log("cookie_name" , cookie);
    if (cookie === undefined)
    {
            //cookie is set but I can't use req.post.xxxx. It"s always undefined
        res.cookie("price", 111, { maxAge: 10000 });
        console.log('cookie has been created successfully');
    } 
    else
    {
        console.log('cookie exists', cookie);
    } 
    next();
});

app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', handshake.token);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

以下代码执行setCookie回调(因为控制台输出显示),并且在控制台上正确定义了变量,但未设置cookie。

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , handshake = require('./routes/handshake')
  , http = require('http')
  , path = require('path');

var app = express();

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());


var setCookie = function (req, res, next) {
    var cookie = req.cookies.cokkieName;
    console.log("cookie_name" , cookie);
    if (cookie === undefined)
    {

        res.cookie("price", 111, { maxAge: 10000 }); 
            //in the console the post.body.xxxx data appears correctly but no cookie!!!
        console.log('cookie has been created successfully',post.body.xxx);
    } 
    else
    {
        console.log('cookie exists', cookie);
    } 
    next();
};
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', setCookie ,handshake.token);
http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

尝试使代码更具可读性引入了太多与我的代码无关的拼写错误。我接受了建议并以下列方式更改了代码,但它仍然没有向客户端写入cookie。

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , handshake = require('./routes/handshake')
  , http = require('http')
  , crypt = require('crypto')
  , io = require('socket.io')
  , db = require('levelup')('./mydb')
  , path = require('path');

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

var cookieMiddleware = function (req, res, next) {
    var cookie = req.cookies.user;
    console.log("cookie_name" , cookie);
    if (cookie === undefined)
    {
        // no: set a new cookie
        var random = Math.random().toString();
        random=random.substring(2,random.length);       
        sessionToken = Date.now()  + random;
        salt = sessionToken + req.body.address;
        sha2 = crypt.createHash('sha256');
        sha2.update(sessionToken);
        var price = req.body.price;
        var encryptedSession = sha2.digest('hex');

    console.log('post body',price );
        res.cookie('user','price' , { maxAge: 100000 });
        console.log('existing cookies', req.cookies);
    } 
    else
    {
        console.log('cookie exists', req.cookies);
    } 
    next(); 
};
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.session({secret: "TheSuperSecretStringForHashing"}));
app.use(express.methodOverride());
app.use(app.router);
//app.use(express.favicon());
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.post('/handshake', cookieMiddleware , handshake.token);
app.get('/', routes.index);
app.get('/users', user.list);


 var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

io = io.listen(server);

io.sockets.on('connection', function (socket) {
      socket.emit('news', { hello: 'world' });
      socket.on('my other event', function (data) {
        console.log(data);
      });
    });

handshake.js处理程序

exports.token = function(req, res){
    req.body.title = 'Payment Portal';
    res.render('payment_init', req.body);
};

1 个答案:

答案 0 :(得分:0)

您正在检查名为cokkieName的Cookie,但您设置的Cookie名称为price

尝试将其更改为:

var cookie = req.cookies.price;

cookie现在应该包含您的Cookie值。