2015-07-13 63 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]);