我需要创建以下过程.我有两个端点,我需要将第二个端点传递给expressejs中第一个端点的结果.我曾想过制作像导游节目一样的东西:
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]);
Run Code Online (Sandbox Code Playgroud)
我应该如何将第一个函数传递给第二个函数?
你需要为req参数创建新属性
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]);
Run Code Online (Sandbox Code Playgroud)