简体   繁体   English

使用函数对象的Node.js自定义中间件

[英]Node.js Custom Middleware Using An Object Of Functions

In Express.js, ihave been having problems with making my own middleware. 在Express.js中,我在制作自己的中间件时遇到了问题。 I know that middleware is supposed to be a function, but can the middleware function be inside an array. 我知道中间件应该是一个函数,但是中间件函数可以在数组内部。 For Example: 例如:

module.js: module.js:

module.exports = {
  function1: function(req, res) {
    console.log('function1'); 
    //second edit.
    I want to return something as well
    return 'hello world';
    //if i add next(); it wont call the next();
  },
  function2: function(req, res) {
     console.log('function2');
  }
}

app.js: app.js:

const express = require('express')
, middleware = require('./module')
, app = express();

app.use(middleware.function1);
app.use(middleware.function2);

app.get('/', (req, res) => {
  //this is an edit: i want to use some code here like
  res.send('Hello World');
  middleware.function1();
});

app.listen(8080);

When i Do This, the webpage just doesn't load. 当我这样做时,网页不会加载。 Any Help? 有帮助吗?

You are missing crucial part next function (which is callback to trigger next middleware in the sequence) in defining middleware functions function1 and function2. 在定义中间件函数function1和function2时,您缺少关键部分的next函数(该回调是触发序列中的下一个中间件的回调)。

Have you seen https://expressjs.com/en/guide/writing-middleware.html ? 您是否看到过https://expressjs.com/en/guide/writing-middleware.html

In below code, you are not passing req, res to the middleware function. 在下面的代码中,您没有将req,res传递给中间件功能。

app.get('/', (req, res) => {
  middleware.function1();
});

OR call it directly as below 或直接如下调用

app.get('/', middleware.function1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM