js控制器中使用Next

js控制器中使用Next

本文介绍了在node.js控制器中使用Next()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注出色的node-express-mongoose-demo应用程序(链接

I am following the wonderful node-express-mongoose-demo app (link

在articles.js控制器中,.load函数具有next()语句,对此我感到困惑-我认为next()仅用于路由,将流程传递给下一个中间件.为什么在控制器内部在此使用next()?以及为什么其他控制器功能(例如.edit,请参见下面的代码)未使用next()..

in the articles.js controller, the .load function has a next() statement and I am confused about it - I thought that next() was only used in routing, passing the flow to the next middleware. why is next() being used here inside a controller? and why are the other controller functions (e.g. .edit ,see code below) NOT using next()..?

 /**
 * Module dependencies.
 */

var mongoose = require('mongoose')
  , Article = mongoose.model('Article')
  , utils = require('../../lib/utils')
  , extend = require('util')._extend

/**
 * Load
 */

exports.load = function(req, res, next, id){
  var User = mongoose.model('User')

  Article.load(id, function (err, article) {
    if (err) return next(err)
    if (!article) return next(new Error('not found'))
    req.article = article
    next()
  })
}

....

/**
 * Edit an article
 */

exports.edit = function (req, res) {
  res.render('articles/edit', {
    title: 'Edit ' + req.article.title,
    article: req.article
  })
}

推荐答案

.load 中间件正在调用 next(),因为它是参数中间件.这些特殊的中间件使您可以为特定的路由参数执行逻辑.如果您有一条类似/users/:id 的路由,那么可以方便地在其中设置 id 的参数中间件,以从数据库中加载该特定用户的配置文件,然后继续到实际的路由处理程序(现在已经可以使用该用户的配置文件了).否则,您可能会发现自己在路由处理程序中针对同一路由路径的不同HTTP动词重复了相同的加载逻辑.

The .load middleware is calling next() because it is a parameter middleware. These special middlewares allow you to perform logic for specific route parameters. This can be handy if you have a route like /users/:id where you could set up a parameter middleware for id that loads that particular user's profile from the database and then continues on to the actual route handler (which now has the user's profile already available to it). Without this, you may find yourself repeating the same loading logic inside route handlers for different HTTP verbs for the same route path.

常规路由处理程序(例如 edit )不使用 next(),因为它们不需要(除非您遇到类似HTTP 500的严重错误)并想调用 next(err)).通常,它们是将响应发送回客户端的响应.

The normal route handlers (e.g. edit) don't use next() because they don't need to (unless you encounter a serious HTTP 500-like error and want to call next(err) for example). They typically are the ones that send the response back to the client.

这篇关于在node.js控制器中使用Next()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:10