Connecting middleware in Node.js/Express
Asked Answered
L

1

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?

Lemming answered 9/9, 2013 at 17:14 Comment(0)
B
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);
});
Bohemia answered 9/9, 2013 at 17:40 Comment(4)
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.Lemming
A good explanation of this is also at #8711169Lemming
@Lemming 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.Bohemia
That you for your help explaining this. This helped a lot.Lemming

© 2022 - 2024 — McMap. All rights reserved.