6

The following is a simple example of a Node.js/Express web server:

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

app.listen(3000);

When this is running, the request http://localhost:3000/Hello-world will generate the response

Hello, you requested /Hello-world.

To learn about middleware, I would like to reimplement this server, but having 'get data', 'manipulate data', and 'output data' contained in separate functions using middleware. I have tried the following, but for this code a request http://localhost:3000/Hello-world gives no response. Only the app.get(..) code seems to execute.

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);

There seems to be something missing that connects the functions together, but what?

rgettman
  • 176,041
  • 30
  • 275
  • 357
user2692274
  • 145
  • 2
  • 5

1 Answers1

4
//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);
});
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Thank you. This works! So, if I understand this correctly: `app.use`-functions are called on any request, and these are executed in the order they are called (so, Step 1 is executed before Step 2). `app.get` is executed on `GET` requests, and these are executed afterwards. – user2692274 Sep 09 '13 at 17:56
  • 1
    A good explanation of this is also at http://stackoverflow.com/questions/8710669/having-a-hard-time-trying-to-understand-next-next-in-express-js – user2692274 Sep 09 '13 at 18:03
  • @user2692274 USUALLY. the GET requests get executed wherever the router goes, which you can adjust with `app.use(app.router)`. Normally it's second-to-last just before error handling routes, but express makes it easy to accidentally put the router too early and things get screwed up. – Peter Lyons Sep 09 '13 at 18:09
  • That you for your help explaining this. This helped a lot. – user2692274 Sep 09 '13 at 18:46