2013-10-29 489 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

相關問題