有没有办法在调用nodejs中的控制器之前调用一个函数

Is there a way to call a function before calling the controllers in nodejs

我的路由文件中定义了多个路由,我想在调用控制器之前在每个路由上调用一个函数。有办法吗?

const express = require('express');
const userController = require('../controllers/user');
const chatController = require('../controllers/chats');
const fileUploadController = require('../controllers/fileUploader');
const instagram = require('../controllers/instagram');

const router = express.Router();

/* Express Routes */
router.post('/login', userController.authenticate);
router.post('/verifyotp', userController.handleTwoFactor);
router.post('/startcheckpoint', userController.startCheckpoint);
router.post('/handle-checkpoint', userController.handleCheckpoint);
router.post('/logout', userController.logout);
router.get('/chatlist', chatController.getChatList);
router.post('/send-message', chatController.sendNewMessage);
router.get('/get-single-chat', chatController.getSingleChat);
router.post('/getoldmessages', chatController.getOlderMessage);
router.post('/uploadfile', fileUploadController.fileUploader);
router.post('/sendaudio', fileUploadController.sendAudio);
router.get('/searchuser', chatController.searchUser);
router.post('/markasread', chatController.markAsRead);
router.post('/muteuser', chatController.muteUser);
router.post('/blockunblockuser', chatController.blockUnblockUser);
router.post('/deletechat', chatController.deleteChat);
router.post('/unsendmessage', chatController.unsendMessage);
router.get('/getunfollowers', chatController.getUnfollowers);
router.post('/unfollow', chatController.unfollowUser);
module.exports = router;

是的,Express 在设计时就考虑到了中间件。您可以在文档 here.

上阅读有关中间件的信息

这是一个使用您的代码的简单示例,可能会有所帮助:

function middleware (req, res, next) {
  console.log('I run before the controller action!')

  next()
}

router.post('/login', middleware, userController.authenticate)

如果您想将一些中间件问题分离到多个不同的中间件中,您甚至可以选择以数组形式提供中间件(第二个参数)。

function firstMiddleware (req, res, next) {
  console.log('I run before the second middleware!')

  next()
}

function secondMiddleware (req, res, next) {
  console.log('I run after the first middleware but before the controller action!')

  next()
}

router.post('/login', [firstMiddleware, secondMiddlware], userController.authenticate)

如果你想在每个路由调用控制器之前调用一个函数,你可以这样做。

const router = express.Router();

router.use(function (req, res, next) {
  console.log('this will be called for every route')
  next()
})
/* Express Routes */