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?
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 onGET
requests, and these are executed afterwards. – Lemming