首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在express Router.route和控制器模式中触发next()?

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

Stack Overflow用户
提问于 2018-07-28 23:34:46
回答 2查看 201关注 0票数 0

在请求到达我的一个api路由之后,我似乎不知道如何实现'next()‘。我想在一切都完成之后做日志记录,而不是在我的api路由之前。我已经在我的路由上实现了控制器模式。我现在只能记录错误,但我想记录所有请求:

代码语言:javascript
复制
//------ 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."
}

非常感谢。

EN

回答 2

Stack Overflow用户

发布于 2018-07-29 00:42:06

我想出了一种触发next的方法,它不是立即发送响应,而是将其分配给res.locals并调用next。以下是基于我上面的代码的更改:

代码语言:javascript
复制
//------ 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提示!:)

票数 1
EN

Stack Overflow用户

发布于 2018-07-28 23:37:18

只需替换

代码语言:javascript
复制
 return res.status(httpStatus.OK).json(book);
 // HOW DO I TRIGGER next()? 

使用

代码语言:javascript
复制
res.status(httpStatus.OK).json(book);
next();

它会起作用的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51572811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档