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