2013-10-29 216 views
2

以下代码显示除我期望的行为之外的一些行为。Node.js - 为什么这些模块不能像我期望的那样工作?


我想到:

GET / - >显示 “欢迎”,并关闭连接

POST /pages - >增量/日志记录计数器;显示“POST功能”,并关闭连接

GET /someRandomPath - >增加/记录计数器;显示404消息


什么我观察:

GET / - >显示 “欢迎”,并关闭连接

POST /pages - >NO增量/日志计数器;显示“在POST功能”,并关闭连接

GET /someRandomPath - >增加/记录计数器;显示404消息


代码:

var express = require('express'); 
var request_counter = 0; 

var app = express() 

    .use(express.basicAuth('test', 'test')) 

    //serve the root (welcome) 
    .get('/', function(req, resp, next) { 
     resp.end('welcome'); 
    }) 

    // count/log the requests 
    .use(function(req, resp, next) { 
     console.log('request# ' + (++request_counter)); 
     next(); 
    }) 

    // serve "/pages" 
    .post('/pages', function (req, resp, next) { 
     console.log('in the POST function'); 
     resp.end('in the POST function'); 
    }) 

    // serve 404 
    .use(function (req, resp) { 
     resp 
      .status(404) 
      .end('BB: not found') 
     ; 
    }) 
; 

module.exports = app; 

为什么计数器不会递增/当我打电话POST /pages登录?

我注意到的一件事是,如果我注释掉//serve the root部分,我会得到我期望的行为。

回答

1

看起来好像您应该在之前定义您的所有中间位置您开始定义路线,如this answer中所述。

您没有明确使用app.use(app.router),但是会在you use app.get时自动调用。

认识到这一点,我很可能会更改您的代码类似于此:

var express = require('express'); 
var request_counter = 0; 

var app = express() 

app.use(express.basicAuth('test', 'test')) 

// count/log the requests for all except '/' 
app.use(function(req, resp, next) { 

    if (req.path != '/') { 
     console.log('request# ' + (++request_counter)); 
    } 

    next(); 
}) 

//serve the root (welcome) 
app.get('/', function(req, resp, next) { 
    resp.end('welcome'); 
}) 

// serve "/pages" 
app.post('/pages', function (req, resp, next) { 
    console.log('in the POST function'); 
    resp.end('in the POST function'); 
}) 

// serve 404 for all the rest 
app.all('*', (function (req, resp) { 
    resp 
     .status(404) 
     .end('BB: not found') 
    ; 
})) 

app.listen(1234); 
+0

啊,这是有道理的!只是要清楚,当你说“中间件”时,你的意思是Connect的东西,就像use()?而像get()和post()这样的Express是“非中间件”? – loneboat

+0

@loneboat - yep; [middlewhere](http://expressjs.com/api.html#app.use)通常在[application routes](http://expressjs.com/api.html#app.VERB)使用'app.use' (非中间地区)使用'app.get','app.post'和'app.all'。 – FriendlyGuy

相关问题