如何解决未处理的承诺拒绝警告

时间:2021-05-25 05:07:58

标签: javascript node.js

我创建了一个简单的注册功能,并添加了一些无法正常工作的检查。 他们给出了错误:

(node:14256) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:558:11)
    at ServerResponse.header (C:\Users\hp\Desktop\Projects\chatapp-backend\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\hp\Desktop\Projects\chatapp-backend\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\hp\Desktop\Projects\chatapp-backend\node_modules\express\lib\response.js:267:15)
    at CreateUser (C:\Users\hp\Desktop\Projects\chatapp-backend\controllers\auth.js:29:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:14256) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14256) [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.

根据我在使用邮递员时的期望,当我输入相同的电子邮件或用户名时,它应该相应地给出消息,但它给出了这样的错误

auth.js 文件:

const Joi=require('joi');
const HttpStatus=require('http-status-codes');
const bcrypt=require('bcryptjs');

const User=require('../models/userModels');
const Helpers=require('../Helpers/helpers');

module.exports={
  async CreateUser(req,res){
    const schema = Joi.object({
      username: Joi.string()
        .min(5)
        .max(10)
        .required(),
      email: Joi.string()
        .email()
        .required(),
      password: Joi.string()
        .min(5)
        .required()
    });

    const validation = schema.validate(req.body);
    res.send(validation);
    console.log(validation);

    const userEmail=await User.findOne({email :(req.body.email)});
    if(userEmail){
      return res.status(HttpStatus.StatusCodes.CONFLICT).json({message: 'Email already exist'});
    }

    const userName=await User.findOne({
      username: (req.body.username)
    });
    if(userName){
      return res.status(HttpStatus.StatusCodes.CONFLICT).json({message: 'Username already exist'});
    }

    return bcrypt.hash(req.body.password,10,(err,hash)=>{
      if(err){
        return res.status(HttpStatus.StatusCodes.BAD_REQUEST).json({message: 'Error hashing password'});
      }

      const body={
        username: Helpers.firstUpper(req.body.username),
        email: Helpers.lowerCase(req.body.email),
        password: hash
      }

      User.create(body).then((user) => {
        res.status(HttpStatus/HttpStatus.StatusCodes.CREATED).json({message: 'USer created successfully',user})
      }).catch(err => {
        res.status(HttpStatus.StatusCodes.INTERNAL_SERVER_ERROR).json({message: 'Error occured'})
      })
    });
}
};

helpers.js 文件

const User = require('../models/userModels');
module.exports={
  firstUpper: username => {
    const name = username.toLowerCase();
    return name.charAt(0).toUpperCase() + name.slice(1);
  },

  lowerCase: str => {
    return str.toLowerCase();
  },
};

2 个答案:

答案 0 :(得分:1)

您尝试发送两次响应,而第一次已经在转换中。我不确定您为什么要将验证发回给客户端,但这会导致问题:

const validation = schema.validate(req.body);
    // return res.send(validation); // or just add this validation to another response 
    console.log(validation);

try {
    
    const userEmail=await User.findOne({email :(req.body.email)});

    if(userEmail){

    return res.status(HttpStatus.StatusCodes.CONFLICT).json({message: 'Email already exist', validation: validation});
    }

    const userName=await User.findOne({
      username: (req.body.username)
    });

    if(userName){
    
    return res.status(HttpStatus.StatusCodes.CONFLICT).json({message: 'Username already exist', validation: validation});
    }
}

catch(console.errror);


此外,当您使用 async/await 时,请使用 try/catch 进行错误处理。您应该查看 this 帖子以了解发生这种情况的原因以及将来如何避免这种情况。

答案 1 :(得分:0)

这是一个流行的错误 - “错误:发送后无法设置标头。” 如果您在发送了 res.send() 等最终请求之后发送数据,您会看到这一点。

 //Don't send anything to your response after this.
 res.send(validation);
//You have multiple res.status after this, and if any of that runs then you will see this error.