const cb0 = function (data, req, res, next) {
console.log('CB0')
next()
}
const cb1 = function (data, req, res, next) {
console.log('CB1')
next()
}
app.get('/example/d', [cb0, cb1], (req, res, next) => {
console.log('the response will be sent by the next function ...')
next()
}, (req, res) => {
res.send('Hello from D!')
})
從上面的代碼中,我傳遞了一個函式陣列,[cb0, cb1]每個函式都需要一些data型別的屬性any和額外的引數,比如req,res和next.
bind早些時候,我嘗試使用概念
傳遞如下格式的資料屬性。app.get('/example/d', [cb0.bind(data), cb1.bind(data)], (req, res, next)
但是如果我使用這個bind概念,那么如何傳遞其他必需的屬性(req,res和next)?有沒有其他方法可以傳遞所有引數,包括data不系結?或者我們在 express 中使用函式陣列有什么限制嗎?
uj5u.com熱心網友回復:
首先,您使用bind不正確(關于您的函式的撰寫方式): bind 的第一個引數是this呼叫函式時使用的值;只有隨后的引數定義了在呼叫時提供函式的引數。所以你想要cb0.bind(null, data)而不是cb0.bind(data).
但是如果我使用這個
bind概念,那么如何傳遞其他必需的屬性(req,res和next)?
(它們是引數,而不是屬性。) Express 在呼叫您的函式時會這樣做。引數將遵循您通過bind. 您的函式已正確設定以處理該訂單 ( data, req, res, next),因此隨著更改,您應該可以開始使用了。
所以:
app.get('/example/d', [cb0.bind(null, data), cb1.bind(null, data)], (req, res, next) => {
// ...
為清楚起見,下面是一個函式的示例,該函式通過bind使用更多引數呼叫系結到它的資料:
顯示代碼片段
function example(data, other) {
console.log(`data = ${JSON.stringify(data)}, other = ${JSON.stringify(other)}`);
}
const ex = example.bind(null, "baked in arg");
// Emulating Express calling the middleware:
ex("passed arg");
旁注:您不必將中間件函式放在陣列中,express 對它們作為離散引數感到滿意:
app.get('/example/d', cb0.bind(null, data), cb1.bind(null, data), (req, res, next) => {
// ...
無論哪種方式都很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447596.html
標籤:javascript 节点.js 打字稿 表示 中间件
下一篇:引數未傳遞給服務器路由器
