【问题标题】:Can i use route inside a controller in express js?我可以在 express js 的控制器内使用路由吗?
【发布时间】:2021-12-20 06:02:51
【问题描述】:

所以我的一个控制器中有这样的东西:

module.exports.authToken = (req, res, next) => {
    const token = req.cookies.jwt;
    //console.log(token);
    if (!token) {
        return res.sendStatus(403);
    }
    try {
        const data = jwt.verify(token, "secret token");
        console.log(data);
        req.userId = data.id;
        return next();
      } catch {
        return res.sendStatus(403);
      }
  };

它被路由调用:

router.get("/protected", authController.authToken, (req, res) => {
    return res.json({ user: { id: req.userId, role: req.userRole } });
  });

我想在我的其他控制器之一中获得该路由的 JSON 响应。我尝试了一些方法,但都没有成功。

【问题讨论】:

  • estas intentando crear un middleware para que el cliente que haga una consulta a esa ruta este autotorizado si o si ?
  • 是的,我想检查用户是否登录

标签: javascript express routes controller


【解决方案1】:

我要做的是将响应抽象为一个函数以供重用:

// the function will just return the data without writing it to the response
function protectedRoute(req) {
    return {user: {id: req.userId, role: req.userRole}};
}

router.get("/protected", authController.authToken, (req, res) => {
    // in the actual handler you can return the response
    return res.json(protectedRoute(req));
});

// make sure the middleware is still being run
router.get("/other_route", authController.authToken, (req, res) => {
    // use the same function to get the response from /protected
    const protectedResponse = protectedRoute(req);
    // do stuff with it
});

【讨论】:

  • 好的,但是我可以这样做,我的其他路由调用另一个控制器,并在这个控制器内部将数据获取到一个变量,就像我使用 /protected 路由一样?
猜你喜欢
  • 2021-09-21
  • 2022-12-03
  • 1970-01-01
  • 2020-02-20
  • 2014-10-24
  • 2012-05-23
  • 2020-11-05
  • 2015-03-07
  • 2021-07-31
相关资源
最近更新 更多