server.js
var connect = require('connect');
var app = connect();
app.listen(3000);
app.use(logger)
.use('/admin', restrict) // 當.use()的第一個參數是一個字符串時,只有URL前綴與之匹配時,Connect纔會調用後面的中間件
.use('/admin', admin)
.use(hello);
// 日誌中間件
function logger(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
}
// 添加中間件
//app.use(logger);
// 第二個中間件
function hello(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.end('hello world');
}
//app.use(hello);
/* 掛載中間件 */
/* 當.use()的第一個參數是一個字符串時,只有URL前綴與之匹配時,Connect纔會調用後面的中間件 */
// 實現HTTP Basic認證的中間件組件
function restricvart(req, res, next) {
var authorization = req.headers.authorization;
/* 用Error做參數調用next,相當於通知Connect程序中出現了錯誤 */
/* 也就是對於這個HTTP請求而言,後續執行的中間件只有錯誤處理中間件 */
if (!authorization) return next(new Error('Unauthorized'));
var parts = authorization.split(' ');
var scheme = parts[0];
var auth = new Buffer(parts[1], 'base64').toString().split(':');
var user = auth[0];
var pass = auth[1];
// 根據數據庫中的記錄檢查認證信息的函數
authenticateWithDatabase(user, pass, function(err) {
if (err) return next(err);
next();
});
}
function admin(req, res, next) {
/* 注意這裏case中用的字符串是/和/users,而不是/admin和/admin/users */
/* 因爲在調用掛載的中間件之前,Connect從req.url中去掉了前綴 */
switch (req.url) {
case '/':
res.end('try /users');
break;
case '/users':
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(['tobi', 'loki', 'jane']));
break;
}
}