NodeJs UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 [英] NodeJs UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

查看:197
本文介绍了NodeJs UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用中间件来执行用户验证任务,以验证用户是否存在,这是我的代码:

Hello I am working in a user verification task using a middleware to verify if the user exist or not, this is my code:

我有一个这样定义的端点:

I have an endpoint defined like this:

app.get("/login/", verifyUser, userController.login); 

这是我的中间件verifyUser:

This is my middleware verifyUser:

function verifyUser(req, res, next) {
  console.log("Midd 1:", req.query);
  let userInfo = userController.findUserOne(req, res);
  console.log("userInfo:" + userInfo);
  next();
}

这是我的控制器方法:

exports.findUserOne = function (req, res) {
  (async () => {
    try {
      var query = db
        .collection("users")
        .where("user", "==", req.query.user)
        .where("password", "==", req.query.password);
      query.get().then(function (querySnapshot) {
        if (querySnapshot.size > 0) {
          const accessToken = generateAccessToken({ name: req.query.user });
          res.json({ accessToken: accessToken });
        } else {
          return res.status(500).send("User doesn't exist:");
        }
      });
    } catch {
      return res.status(500).send(error);
    }
  })();
};

调用登录端点后,我收到下一条错误消息:

After calling the login endpoint I am getting the next error message:

(node:12468) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
    at ServerResponse.header (C:\Tools\Node\From Github\NodeAndReact-FullStack\server\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Tools\Node\From Github\NodeAndReact-FullStack\server\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Tools\Node\From Github\NodeAndReact-FullStack\server\node_modules\express\lib\response.js:267:15)
    at C:\Tools\Node\From Github\NodeAndReact-FullStack\server\controllers\users\userController.js:54:15
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:12468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12468) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我正在尝试在控制器中处理我的异步块,但是根据外观看来,问题似乎与此有关.实际上,我不太确定这是否是实施此验证的最佳方法,还是遇到与异步代码相关的问题.

I am handling my async block in the controller with a try, catch, but according to the looks it seems like the issue is related with that. In fact I'm not pretty sure if it is the best way to implement this verification or I am getting an issue related with the async code.

推荐答案

这是因为userController.findUserOne是异步函数,而您在调用它时没有任何等待.所以在您的代码的这一部分

it's because userController.findUserOne is an async function while you call it without any await behind it. so in this part of your code

function verifyUser(req, res, next) {
    console.log("Midd 1:", req.query);
    let userInfo = userController.findUserOne(req, res);
    console.log("userInfo:" + userInfo);
    next();
}

当您调用 userController.findUserOne(req,res); 时,由于异步函数返回了一个Promise,它也会返回一个Promise,而不是您想要的真实用户信息.

when you call userController.findUserOne(req, res); since async functions return a promise, it will return a promise as well not the real user info you want.

解决方案是将verifyUser函数更改为以下内容:

the solution is to change verifyUser function to something like this:

async function verifyUser(req, res, next) {
    try {
        console.log("Midd 1:", req.query);
        let userInfo = await userController.findUserOne(req, res);
        console.log("userInfo:" + userInfo);
        next();
    } catch(error){
        //handle exceptions here
    }
}

这篇关于NodeJs UnhandledPromiseRejectionWarning:错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆