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
部分,我會得到我期望的行爲。
啊,這是有道理的!只是要清楚,當你說「中間件」時,你的意思是Connect的東西,就像use()?而像get()和post()這樣的Express是「非中間件」? – loneboat
@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