5

以下是 Node.js/Express Web 服务器的简单示例:

var express = require('express');
var app = express();

app.get('/*', function(req, res){
   res.end('Hello, you requested ' + req.url + '.');
});

app.listen(3000);

当它运行时,请求http://localhost:3000/Hello-world将生成响应

Hello, you requested /Hello-world.

要了解中间件,我想重新实现此服务器,但使用中间件将“获取数据”、“操作数据”和“输出数据”包含在单独的函数中。我试图关注,但对于此代码,请求http://localhost:3000/Hello-world没有响应。只有app.get(..)代码似乎在执行。

var express = require('express');
var app = express();

// Step 1: get input
app.get('/*', function(req, res){
   req['testing'] = req.url;
});

// Step 2: manipulate data
app.use('/*', function(req, res, next) {
   req['testing'] = 'Hello, you requested ' + req['testing'];
   return next();
});

// Step 3: send output  
app.use('/*', function(req, res, next) {
    res.end(req['testing']);
    return next();
});

app.listen(3000);

似乎缺少将功能连接在一起的东西?

4

1 回答 1

3
//This needs to be MIDDLEWARE not a route handler
// Step 1: get input
app.use(function(req, res, next){
   req.testing = req.url;
   next();
});

// Step 2: manipulate data
app.use(function(req, res, next) {
   req.testing = 'Hello, you requested ' + req.testing;
   next();
});

// Step 3: send output  
app.get('/*', function(req, res) {
    res.end(req.testing);
});
于 2013-09-09T17:40:02.540 回答