Node.js – 为什么这些模块不能像我期望的那样工作?

下面的代码显示了一些我期望的行为。


我期望的是:

GET / – >显示“欢迎”并closures连接

POST /pages – >增加/logging计数器; 在POSTfunction中显示“,然后closures连接

GET /someRandomPath – >增加/logging计数器; 显示404消息


我观察到:

GET / – >显示“欢迎”并closures连接

POST /pages – > 没有增加/计数器的日志; 在POSTfunction中显示“,然后closures连接

GET /someRandomPath – >增加/logging计数器; 显示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时,为什么计数器不会增加/logging?

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

开始定义路线之前 ,看起来好像你应该定义所有的中间地点,正如在这个答案中所指出的那样。

你没有明确使用app.use(app.router) ,但是当你使用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);