Search code examples
node.jsexpressmiddlewarenode.js-connect

Connecting middleware in Node.js/Express


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?


Solution

  • //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);
    });