‘next’参数在Node.js Express中的’中间件函数’中是如何工作的?

huangapple go评论75阅读模式
英文:

How does the 'next' parameter in 'middleware function' work in Node.js' Express?

问题

  1. "next" 参数的作用是什么?它是否会重定向到 "下一个中间件函数"?如果是的话,是如何实现的?
  2. 如果不存在 "第二个中间件",会发生什么?
  3. 如果我们不使用 "next",会发生什么?
  4. 我们能在 "next" 中重定向到自定义中间件吗?
英文:

I am working on Nodejs and using "Express js", Right now i am working on "middleware function", here is my current code

const express = require('express')
const app = express()

const myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

app.get('/', (req, res) => {
  res.send('Hello World!')
})

I am confuse regaring "next" parameter,I have following question regarding middleware function

  1. what is use of "next" ? is this redirect to "next middlware function" ? if yes then how ?
  2. if there is not "second middleware" exist then what will happen ?
  3. if we not use "next" then what will happen ?
  4. can we redirect to custom middleware inside "next" ?

答案1

得分: 2

  1. 是的,调用 next 是重要的,因为这允许 express.js 转移到下一个中间件,否则它将处于悬空状态,应用程序将无法正常工作。

  2. 您的请求将到达路由处理程序,您将收到一个带有消息 'Hello World' 的响应。

  3. 如果您不调用 next,请求将被终止,应用程序将保持挂起状态。

  4. 是的,您可以使用 next 重定向到自定义中间件函数。每当 next 带有参数被调用时,express 将其视为错误消息。您可以定义自定义错误处理中间件来根据需要进行重定向。

英文:
  1. Yes, calling next is important because this allows the express.js to move to the next middleware, otherwise it will be in a dangling position and the app will not work appropriately.

2)Your request will reach the route handler and you will get a response with the message 'Hello World"

3)If you don't call next, the request will be terminated and the app will remain hanging

4)Yes, you can redirect to the custom middleware function using next. Whenever next is called with an argument, expresses takes it as an error message. You can define, custom error-handling middleware to direct it according to your needs.

答案2

得分: 1

只需next()表示继续执行第一个匹配的路由路径。如果您从不调用next()response,请求将停留在中间件上。中间件存在的原因有两个:

  1. 数据操作,您可以向request.body等添加额外的值以供以后使用。
  2. 阻止,如果出现任何意外情况,您可以立即响应而无需继续执行匹配路由路径。

例如:

// 请求发送到 /users/user1

const myLogger = function (request, res, next) {
    console.log('LOGGED');
    next();
}

router.use(myLogger);

router.post('/users*', (request, res, next) => {
    if (!isAdmin(request)) {
        return res.status(401).json();
    }

    return next();
})

router.post('/users/:id', (request, res, next) => {
    res.json(getUser());
})

function getUser() {
    return { name: 'Lorem', surname: 'Ipsum' }
}

function isAdmin(request) {
    return true;
}
英文:

Simply next() means continue with the first following path matching route. If you never call next() or response, the request will be stuck on that middleware. Middleware is there for 2 reasons:

  1. manipulating data, you can add extra values into e.g. request.body for later uses
  2. blocking, if anything is unexpected you can respond without continuing to path matching routes.

For example:

// request sent to /users/user1

const myLogger = function (request, res, next) {
    console.log('LOGGED');
    next();
}

router.use(myLogger);

router.post('/users*', (request, res, next) => {
    if (!isAdmin(request)) {
        return res.status(401).json();
    }

    return next();
})

router.post('/users/:id', (request, res, next) => {
    res.json(getUser());
})

function getUser() {
    return { name: 'Lorem', surname: 'Ipsum' }
}

function isAdmin(request) {
    return true;
}

huangapple
  • 本文由 发表于 2023年5月28日 18:53:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76351110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定