2015-07-13 60 views
0

我需要创建以下过程。我有两个端点,我需要将expressejs中第一个端点的结果传递给第二个端点。我曾想过要制作类似指南的节目:expressjs中的连锁请求

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]); 

我应该如何将第一个函数的结果传递给第二个函数?

回答

5

你需要像

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]); 
创造新的属性REQ参数
2

简单的事情,

只需添加一个链的结果,请求对象,这样你就可以访问另一个该对象。

这是你的代码。

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]);