【问题标题】:What is the next() function in express.js middlewares [duplicate]express.js 中间件中的 next() 函数是什么[重复]
【发布时间】:2017-12-01 16:14:24
【问题描述】:

我很难理解接下来在这个 Express.js 示例中做什么以及为什么在这里使用它。

这是我处理路线的文件。

 const express = require('express');
 const controller = require('../controllers/myappcontroller');
 const myroutes = express.Router();
 const apphelper = require('../services/appservices/apphelper');

 myroutes.get('/', apphelper.mycoolfunction, controller.index);

这是 apphelper.js 文件的内容

require('isomorphic-fetch');


function mycoolfunction(req, res, next) {
  fetch('someurl')
  .then((fetchRes) => {
    return fetchRes.json();
  }).then((jsonFetchRes) => {
    res.locals.firstname = jsonFetchRes.contents.firstname[0].firstname;
    next();
  }).catch((err) => {
    console.log(err);
    res.locals.firstname = 'not available';
    next();
  });
}

module.exports = {
  mycoolfunction: mycoolfunction,
};

为什么参数中有“next”,为什么要在函数中使用?是不是这样

【问题讨论】:

  • 跳转到下一个中​​间件。如果你有.get('/', func1, func2, func3),那么func1中的next()会跳转到func2,而func2中的next()会跳转到func3。
  • 所以在这个例子中,如果我没有“下一个”,它会停在res.locals.firstname= 'not available'; 并且不做任何其他事情?并且由于“next”的存在,它运行了行中的下一个参数,在这种情况下,controller.index 对吗?
  • 是的,就是这样
  • 太好了,非常感谢

标签: javascript node.js express


【解决方案1】:

很简单,它告诉您的应用运行下一个中间件。

【讨论】:

  • 这有点轻...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-01
  • 2019-04-07
  • 2016-12-28
  • 1970-01-01
  • 2023-01-31
  • 2011-03-18
相关资源
最近更新 更多