Reputation: 14219
I need to create the following process. I have two endpoints and I need to pass to the second endpoint the result of the first endpoint in expressejs. I have thought to make something like the guide shows:
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
var cb2 = function (req, res) {
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2]);
How should I pass to the second one function the result produced by the first one?
Upvotes: 0
Views: 2198
Reputation: 1092
you need to create new property to req parameter like
var cb0 = function (req, res, next) {
// set data to be used in next middleware
req.forCB0 = "data you want to send";
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
// accessing data from cb0
var dataFromCB0 = req.forCB0
// set data to be used in next middleware
req.forCB1 = "data you want to send";
console.log('CB1');
next();
}
var cb2 = function (req, res) {
// accessing data from cb1
var dataFromCB2 = req.forCB1
// set data to be used in next middleware
req.forCB2 = "data you want to send";
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2]);
Upvotes: 5
Reputation: 7688
Simple thing,
Just add result of one chain to request object, so you can access that object in another.
Here is your code.
var cb0 = function(req, res, next) {
req["CB0"] = "Result of CB0";
console.log('CB0');
next();
}
var cb1 = function(req, res, next) {
req["CB1"] = "Result of CB1";
console.log('CB1: Result of CB0: ' + req["CB0"]);
next();
}
var cb2 = function(req, res) {
console.log('CB2: Result of CB0: ' + req["CB0"]);
console.log('CB2: Result of CB1: ' + req["CB1"]);
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2]);
Upvotes: 2