2017-06-06 31 views
2

res.render回調參數的用途是什麼?Node.js中Express 4.0中的res.render回調參數的用途是什麼?

在這種情況下,人們會想要使用這種回調參數,因爲模板已經被指定爲第一個參數?

下面是從文檔代碼:

// send the rendered view to the client 
res.render('index'); 

// if a callback is specified, the rendered HTML string has to be sent explicitly 
res.render('index', function(err, html) { 
    res.send(html); 
}); 

// pass a local variable to the view 
res.render('user', { name: 'Tobi' }, function(err, html) { 
    // ... 
}); 

我理解的前兩個參數的目的,但不是最後一次。

回答

2

通過回調,您可以在發送之前攔截呈現的模板。在發送給客戶端之前,您可能需要將其縮小或進行其他修改。

從文檔:

如果提供,則該方法返回兩個可能的錯誤和渲染串,但不執行自動響應。

+0

謝謝。這是有道理的,人們希望在發送之前縮小模板。你有沒有其他修改的情況可能對利用這個回調參數有用? – roadtocode

+0

@roadtocode取決於你想做什麼......你可以用它來做任何你需要的。 – Brad

相關問題