1

我运行 localhost:3000/name/john,创建一个 cookie,然后 localhost:3000/name 以显示 cookie 我有一个控制台错误“TypeError: Can not read property 'name' of undefined”

看我的代码

 var express = require('express')
     , http = require('http') 
     , path = require('path') ;

var app = express();        

        app.configure(function(){
            app.set('port', process.env.PORT || 3000);
            app.use(express.bodyParser()) ;
            app.use(express.methodOverride()) ;
            app.use(app.router);

            app.use(express.cookieParser());  
            app.use(express.session({ secret: 'secret'}));
        }) ;

      app.get('/name/:name', function(req, res){
            res.cookie('name' , req.params.name).send('<p>the cookie <a href="/name">Go here</a></p>') ;
       });

      app.get('/name', function(req, res){
          console.log(req.cookies.name);
          res.send("index");
      });  

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

如何解决这个问题呢 ?谢谢

4

1 回答 1

1

如下修改您的 app.configure 代码。

app.configure(function(){
      app.set('port', process.env.PORT || 3000);
      app.use(express.bodyParser()) ;
      app.use(express.methodOverride()) ;
      app.use(express.cookieParser());  
      app.use(express.session({ secret: 'secret'}));
      app.use(app.router);
}) ;

看看http://expressjs.com/api.html#app.use。这里的问题在于中间件优先级。

于 2013-04-15T05:50:41.763 回答