Express 500 TypeError:无法读取未定义的属性'get'

时间:2013-02-04 10:47:48

标签: javascript node.js express

此示例取自Node Cookbook,但使用Express 3.1.0:

app.js

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

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());

  app.use(express.cookieParser('kooBkooCedoN'));
  app.use(express.session());
  app.use(require('./login'));

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

// --------------------------
// MODIFICATION IS MADE HERE!
// --------------------------
app.configure(function(){
  app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
  });
});

app.get('/', routes.index);
app.post('/', routes.index);
app.del('/', routes.index);
app.get('/:page', routes.index);

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

我已根据以下建议对代码进行了一些修改: Migrating Express.js 2 to 3, specifically app.dynamicHelpers() to app.locals.use?

login.js

var users = {'dave' : 'expressrocks'};

module.exports = function (req, res, next) { var method = req.method.toLowerCase(), //cache the method
    user = req.body.user,
    logout = (method === 'delete'),
    login = (method === 'post' && user),
    routes = req.app.routes.routes[method];

  if (!routes) { next(); return; }

  if (login || logout) {
    routes.forEach(function (route) {
      if (!(req.url.match(route.regexp))) {
        console.log(req.url);
        req.method = 'GET';
      }
    }); 
  }
  if (logout) {
    delete req.session.user; 
  }
  if (login) {
    Object.keys(users).forEach(function (name) {
      if (user.name === name && user.pwd === users[name]) {
        req.session.user = {
          name: user.name,
          pwd: user.pwd
        };
      }
    }); 
  }
  if (!req.session.user) { req.url = '/'; } 
  next(); 
};

login.jade

if user
  form(method='post')
    input(name="_method", type="hidden", value="DELETE")
    p Hello #{user.name}!
      a(href='javascript:', onClick='forms[0].submit()') [logout]
else
  p Please log in
  form(method='post')
    fieldset
      legend Login
      p
        label(for="user[name]") Username:
        input(name="user[name]")
      p
        label(for="user[pwd]") Password:
        input(type="password", name="user[pwd]")

      input(type="submit")

结果 从终端登录

错误来自该行: routes = req.app.routes.routes [method]; login.js

TypeError: Cannot read property 'get' of undefined
    at Object.module.exports [as handle] (/home/chiasyan/Desktop/login/login.js:8:35)
    at next (/home/chiasyan/Desktop/login/node_modules/express/node_modules/connect/lib/proto.js:199:15)
    at store.get.next (/home/chiasyan/Desktop/login/node_modules/express/node_modules/connect/lib/middleware/session.js:309:9)
    at /home/chiasyan/Desktop/login/node_modules/express/node_modules/connect/lib/middleware/session.js:333:9
    at /home/chiasyan/Desktop/login/node_modules/express/node_modules/connect/lib/middleware/session/memory.js:50:9
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

更新 我更改了 routes = req.app.routes .routes [method]; ,但仍然存在轻微错误。

login.jade 中找不到用户变量(用户 login.js中定义一次

ReferenceError: /home/chiasyan/Desktop/login/views/login.jade:1
  > 1| if user
    2|   form(method='post')
    3|     input(name="_method", type="hidden", value="DELETE")
    4|     p Hello #{user.name}!

user is not defined

来自Node Cookbook的报价

  

在routes / index.js中,我们现在可以简单地使用以下代码:

index.js

exports.index = function (req, res) { 
  res.render('index', {title: 'Express'}); 
};

Node Cookbook的另一个引用

  

由于我们不再使用路线,因此我们没有机会通过req.session。用户通过res.render。但是,我们可以使用   相反,动态助手。动态助手可以访问req和res   对象,它们是在渲染视图之前调用的。任何属性   我们传递给动态助手对象被推送到Jade视图中   局部变量。

由于我无法在Express 3. *中使用动态助手,所以在 app.js 中我已更改为:

app.configure(function(){
  app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
  });
});

2 个答案:

答案 0 :(得分:1)

您提及的行中有错误:

routes = req.app.routes.routes[method];

你应该使用

routes = req.app.routes[method];

顺便说一句,您对此代码的结果进行检查的目的是什么?

更新:要将用户信息传递到Jade视图,您需要在渲染调用中传递此信息。例如:

# Assuming you've got the user information in req.session.user 
console.log(req.session.user);
res.render('login', {user: req.session.user});

答案 1 :(得分:1)

我现在正在运行代码,但我不确定它是否正确。请告知是否应该进行任何纠正。

我修改了

app.configure(function(){
  app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
  });
});

app.use(function(req, res, next){
  res.locals.user = req.session.user;
    next();
});

并将其放在以下行

之后
app.use(require('./login'));

除了Hector Correa在这篇文章中给出的答案之外,这里是修正后的完整工作代码。

<强> app.js

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

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());

  app.use(express.cookieParser('kooBkooCedoN'));
  app.use(express.session());
  app.use(require('./login'));

  app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
  });

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.post('/', routes.index);
app.del('/', routes.index);
app.get('/:page', routes.index);

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

<强> login.js

var users = {'dave' : 'expressrocks'};

module.exports = function (req, res, next) { var method = req.method.toLowerCase(), //cache the method
    user = req.body.user,
    logout = (method === 'delete'),
    login = (method === 'post' && user),
    routes = req.app.routes[method];

  if (!routes) { next(); return; }

  if (login || logout) {
    routes.forEach(function (route) {
      if (!(req.url.match(route.regexp))) {
        console.log(req.url);
        req.method = 'GET';
      }
    }); 
  }
  if (logout) {
    delete req.session.user; 
  }
  if (login) {
    Object.keys(users).forEach(function (name) {
      if (user.name === name && user.pwd === users[name]) {
        req.session.user = {
          name: user.name,
          pwd: user.pwd
        };
      }
    }); 
  }
  if (!req.session.user) { req.url = '/'; } 
  next(); 
};