【问题标题】:How to create custom middleware in express?如何在 express 中创建自定义中间件?
【发布时间】:2020-02-01 08:53:04
【问题描述】:

我需要带有路由的自定义中间件,并承诺执行特定任务。以下是需要在此处输入代码的示例代码:

   function middle(){
   // some code;
   }
   app.get('/', middle, function (req, res) {
      console.log('url is working');
      res.send("Chat server is working!");
   });

【问题讨论】:

    标签: node.js express promise


    【解决方案1】:

    您的中间件函数需要具有签名:function middle(req, res, next),并且您需要在中间件函数的末尾调用 next(),以便它移动到链中的下一个函数,因此根据您的示例代码如下所示:

     function middle(req, res, next){
       // some code;
       next();
     }
     app.get('/', middle, function (req, res) {
        console.log('url is working');
        res.send("Chat server is working!");
     });
    

    【讨论】:

      【解决方案2】:

      当你想发出custom middleware时,你必须调用next() method。它告诉快递它已经完成了对请求的处理。如果你不调用next() method,你的服务器将time out.

       app.use((req,res,next)=> {
         //some code
          next();
      });
      
      app.get('/',(req,res)=> {
          console.log('url is working');
          res.send('chat server is working');
      });
      app.listen(4000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        • 2016-04-14
        • 2012-07-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多