[英]how to solve UnhandledPromiseRejectionWarning on node?
I'm trying to make an API for learning purpose.我正在尝试制作一个 API 用于学习目的。 There's nothing wrong with the API.
API 没有任何问题。 I get the response I want.
我得到了我想要的回应。 But the problem is, when I look at the terminal, I get an error like this:
但问题是,当我查看终端时,我收到如下错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
UnhandledPromiseRejectionWarning:未处理的 promise 拒绝。 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().
此错误源于在没有 catch 块的情况下抛出异步 function 内部,或拒绝未使用.catch() 处理的 promise。
It warn me that permission rejection are not handled will terminate the Node.js.它警告我,不处理权限拒绝将终止 Node.js。
Console LOG控制台日志
(node:8721) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (/backend/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/backend/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/backend/node_modules/express/lib/response.js:267:15)
at exports.apiFormat (/backend/handlers/errorHandlers.js:85:21)
at /backend/middlewares/auth.js:31:11
at allFailed (/backend/node_modules/passport/lib/middleware/authenticate.js:107:18)
at attempt (/backend/node_modules/passport/lib/middleware/authenticate.js:180:28)
at Strategy.strategy.fail (/backend/node_modules/passport/lib/middleware/authenticate.js:302:9)
at verified (/backend/node_modules/passport-local/lib/strategy.js:82:30)
at /backend/middlewares/passport.js:69:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:8721) 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:8721) [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 make it for same json resonse format api.我为相同的 json 共振格式 api 制作它。 ( errorHandlers.js)
(errorHandlers.js)
exports.apiFormat = (statusCode, responseCode, message, success, data, res) => {
try {
return res.status(statusCode).json({
message: message,
success: Boolean(success),
data: data,
status: Number(responseCode),
});
} catch (error) {
res.status(500).json({
message: "Internal Server Error",
});
}
};
Middleware for Authentication using passport.js auth.js使用 passport.js auth.js进行身份验证的中间件
exports.login = async (req, res, next) => {
try {
await validateField(req, res);
await passport.authenticate("login", async (err, user) => {
if (err || !user) {
apiFormat(
process.env.UNAUTORIZED_CODE,
process.env.FAILURE_RESPOSNE_CODE,
"Authentication Failed.",
false,
null,
res
);
}
try {
req.login(user, { session: false }, (err) => {
if (err) {
apiFormat(
process.env.UNAUTORIZED_CODE,
process.env.FAILURE_RESPOSNE_CODE,
"Authentication Failed.",
false,
null,
res
);
}
const tokenData = {
id: user.id,
name: user.name,
email: user.email,
role: user.role,
};
const accessToken = jwt.sign(
tokenData,
"access_token",
{
expiresIn: "8h",
}
);
tokenData.accessToken = accessToken;
req.tokenData = tokenData;
});
} catch (error) {
next(error);
}
next();
})(req, res, next);
} catch (error) {
next(error);
}
//Validate Userinput Field
};
I use express-validator to validate the post data.我使用 express-validator 来验证发布数据。
validateField(req, res)
验证字段(req, res)
const { validationResult } = require("express-validator"); const { apiFormat } = require("../handlers/errorHandlers"); exports.validateField = async (req, res) => { try { const errors = await validationResult(req); const extractedErrors = []; if (.errors.isEmpty()) { errors:array({ onlyFirstError. true }).map((err) => extractedErrors.push(err;msg)). } if (extractedErrors.length > 0) await apiFormat( process.env,UNPROCESSABLE_ENTITY_CODE. process.env,FAILURE_RESPOSNE_CODE, extractedErrors[0], false, null; res ). } catch (err) { res.status(500):json({ message, "Internal Server Error"; }); } };
passport.js:护照.js:
passport.use(
"login",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
session: false,
},
(email, password, done) => {
try {
User.findOne({
email: email,
})
.then((user) => {
if (user === null) {
return done(null, false);
}
bcrypt.compare(password, user.password).then((response) => {
if (response !== true) {
return done(null, false);
}
return done(null, user);
});
})
.catch((err) => {
return done(err);
});
} catch (err) {
return done(err);
}
}
)
);
Api route Api路线
router.post(
"/login",
validator.loginUser,
auth.login,
catchErrors(userController.login)
);
validator.loginUser验证器.loginUser
exports.loginUser = [
check("email")
.exists()
.withMessage("Email is required")
.isEmail()
.normalizeEmail()
.withMessage("Please insert a valid Email"),
check("password")
.not()
.isEmpty()
.withMessage("Password is required")
.isLength({ min: 8 })
.withMessage("Please enter password with minimum 8 character")
.trim()
.escape(),
];
Can you please tell me where i am wrong?你能告诉我我哪里错了吗? And why i am getting such error UnhandledPromiseRejectionWarning?
为什么我会收到这样的错误 UnhandledPromiseRejectionWarning?
validationResult()
Returns the result object but not promise. validationResult()
返回结果 object 但不返回 promise。 You are using await
to wait for a Promise object.您正在使用
await
等待 Promise object。
Remove await
from your code to prevent the error:从代码中删除
await
以防止出现错误:
const errors = validationResult(req);
// .. and your error variable will have arrays of error.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.