2013-04-14 149 views
1

我運行localhost:3000/name/john,創建一個cookie 然後localhost:3000/name顯示cookie 我有一個控制檯錯誤「TypeError:Can not read property'name'未定義」如何創建會話express.js

看我的代碼

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')); 
    }); 

如何解決這個問題呢?謝謝

+0

您是否在您的獲取請求中傳遞:name參數?也閱讀這一個http://stackoverflow.com/questions/14006190/deal-and-keep-node-js-express-sessions –

+1

我找到解決方案閱讀鏈接 http://stackoverflow.com/questions/10645792/節點-JS-和-EXPRESS-如何閱讀-A-庫克,但是,是-未定義 –

回答

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。問題在於中間件的優先級。