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 to 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?
//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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With