如何在Express中创建自定义中间件?

时间: 2024-04-16 admin IT培训

如何在Express中创建自定义中间件?

如何在Express中创建自定义中间件?

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

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

您的中间件函数需要具有签名: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!");
 });