繁体   English   中英

如何在快速Router.route和控制器模式中触发next()?

[英]How to trigger next() in express Router.route and controller pattern?

在请求到达我的api路由之一后,我似乎无法弄清楚如何实现“ next()”。 我想在所有步骤完成后而不是在api路由之前进行日志记录。 我已经在路由上实现了控制器模式。 我现在只能记录错误信息,但是我想记录所有请求:

//------ api/index.js
import routes from './routes/index.route';

app.use('/api', routes);


// ??? HOW TO HANDLE next() called in "/api routes"
// only handles incoming requests not found in "/api routes"
app.use((req, res, next) => {
  // logic here...
  next(error);
});


// global error handler
app.use((error, req, res, next) => {
  // logging logic here...
});



//------ routes/index.route.js
import express from 'express';
import userRoutes from './user.route';
import bookRoutes from './book.route';

const router = express.Router();

router.use('/user', userRoutes);
router.use('/book', bookRoutes);



//------ routes/book.route.js
import express from 'express';
import bookCtrl from './../controllers/book.controller';

const router = express.Router();
router.route('/:bookId').get(bookCtrl.getBook);




//------ controllers/book.controller.js
export const getBook = async (req, res, next) => {
  const book = // get book logic here;

  return res.status(httpStatus.OK).json(book);

  // HOW DO I TRIGGER next()?  
  // I tried this approach as well: 

  // res.status(httpStatus.OK).json(book);
  // next();

  //however, it would say, "Error: Can't set headers after they are sent."
}

非常感谢。

只需更换

 return res.status(httpStatus.OK).json(book);
 // HOW DO I TRIGGER next()? 

res.status(httpStatus.OK).json(book);
next();

它将起作用。

我想出了一种触发下一个的方法,该方法不是立即发送响应,而是将其分配给res.locals并调用next。 这是根据我上面的代码所做的更改:

//------ api/index.js
// handle next() event coming from "/api routes"
// and also handles incoming requests not found in "/api routes"
app.use((req, res, next) => {
  if (res.locals.status) {
    const { status, responseData } = res.locals;
    res.status(status).json(responseData);
    // logging logic here...
  } else {
    // error logic here...
    // forward this error into the global error handler
    next(error);
  }
});



// controllers/book.controller.js
export const getBook = async (req, res, next) => {
  // get book logic here..
  const book = // get book logic here;

    res.locals = {
      status: httpStatus.OK,
      responseData: {
        book,
      },
    };

    next();
}

感谢@destoryer提供的res.json提示! :)

暂无
暂无

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

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