簡體   English   中英

Express:next() 如何與多個 Route 處理程序一起工作?

[英]Express: How does next() work with multiple Route handlers?

我是 Express 的新手,我對next()在這種情況下的工作方式感到困惑:

//Route 1
app.get('/user/:id', function (req, res, next) {
  console.log('ID:', req.params.id)
  next()
}, function (req, res, next) {
  res.send('User Info')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
  res.end(req.params.id)
})

在上面的例子中,執行順序是什么? 從理論上講, res.end(req.params.id)是否比res.send('User Info')執行得早? (即使 res.end() 將結束請求-響應循環。)在這種情況next()做什么?

或者考慮另一種情況:

//Route 1
app.get('/user/:id', function (req, res, next) {
  console.log('1')
  next()
}, function (req, res, next) {
  console.log('2')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
  console.log('3')
})

打印什么序列?

Express 中間件是在對 Express 服務器的請求的生命周期中執行的功能。 每個中間件都可以訪問它附加到的每個路由(或路徑)的 HTTP 請求和響應。 事實上,Express 本身完全是折衷的中間件功能。

中間件 function 根據其用法有 2/3/4 個參數,如下所示:

function (error, request, response, next) {}

當router獲得active express會從第一個中間件開始執行,next用於將執行傳遞給列表中的后續中間件。

app.get('path', 'middleware 1', 'middleware 2', 'middleware 3', ... so on)

您想了解的案例:

app.get('/user/:id', function (req, res, next) {
  console.log('1')
  next()
}, function (req, res, next) {
  console.log('2')
})

// Route 2
app.get('/user/:id', function (req, res, next) {
  console.log('3')
})

您的路由是相同的,express 將始終執行第一個匹配的路由,並且將執行使用 next 將執行傳遞給下一個中間件的route 1 o/p 永遠是:

1
2

在上面的例子中,執行順序是什么? 理論上,res.end(req.params.id)是不是先於res.send('User Info')執行? (即使 res.end() 將結束請求-響應循環。)在這種情況下 next() 做什么?

Route1 將被執行,一旦您發送響應,Express 就會在內部調用 next 來打包響應並發送。

next function 是 Express 路由器中的 function,它在被調用時會執行當前中間件之后的中間件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM