代码之家  ›  专栏  ›  技术社区  ›  Joseph K.

在自定义express函数中返回res和next

  •  -1
  • Joseph K.  · 技术社区  · 5 年前

    res next 在express函数中:

    const customfunction = async (req, res, next) => {
     try {
       // how do I set cookie and return next()?
       return res.cookie('someToken', someToken, {
         signed: true,
         // etc...
         }
       );
      return next();
     } catch (err) {
       // catch here, for example, return res.status(401).clearCookie...
     }
    }
    
    0 回复  |  直到 5 年前
        1
  •  0
  •   jfriend00    5 年前

    一个express请求处理程序(类似于传递给 app.get() router.post() 或者类似的东西)不关注来自该处理程序的返回值。

    return 在这样的处理程序中,只用于流控制,以停止函数的进一步执行。

    return res.cookie(...);
    return next();
    

    这毫无意义,因为 return next() 将永远不会执行代码行,因为函数已在该行上返回。

    如果这是中间件,并且您希望其他请求处理程序仍有机会处理此请求,那么您将需要如下内容:

    const customfunction = async (req, res, next) => {
        res.cookie('someToken', someToken);
        next();
    };
    

    似乎没有任何理由 try/catch

    但是,如果你真的想 尝试/抓住 ,您可以这样做:

    const customfunction = async (req, res, next) => {
        try {
            res.cookie('someToken', someToken);
            next();
        } catch(e) {
            // make sure logs can see that this unexpected error is happening
            console.log("customFunction error", e);
            res.clearCookie('someToken');
            res.status(500).send("Internal Error");   // probably want a more glamorous error page
        }
    };