我将postman与nodejs和MySQL一起使用。
中间件
const notFound = (req, res, next) => {
const error = new Error(`Not Found -${req.originalUrl}`);
res.status(404);
next(error);
};
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
export { notFound, errorHandler };
在这里,我尝试使用NotFound
和ErrorHandler
作为AuthUser
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select @uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT @uid := NULL) init_var where email=?;select @finaluid:= `user_id` from user_type, (SELECT @finaluid := NULL) init_var where user_id =@uid AND type='customer';select customer_id, password from customer where user_id =@finaluid;";
db.query(sql, [email], (err, result) => {
if (err) throw err;
if (result) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["@finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401);
throw new Error("Invalid email or password");
}
}
} else {
res.status(401);
throw new Error("Invalid email or password");
}
});
});
为了访问notfound的和
errorhandler,我在server.js中使用
app.use`,如下所示,
app.use(notFound);
app.use(errorHandler);
我该怎么解决这个?所以,这也将帮助我在前端显示错误。
当您得到空结果时,就会出现这种错误。您应该首先检查结果的长度,然后对其使用属性或索引。
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select @uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT @uid := NULL) init_var where email=?;select @finaluid:= `user_id` from user_type, (SELECT @finaluid := NULL) init_var where user_id =@uid AND type='customer';select customer_id, password from customer where user_id =@finaluid;";
db.query(sql, [email], (err, result) => {
try {
if (err) throw err;
if (result.length > 0) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["@finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401); // this else is calling up for (If you use incorrect password)
throw new Error("Invalid email or password");
}
}
} else {
res.status(401).send({message: 'Results not found'}); // change this to send error message to the frontend, you can really customise it based on your needs.
// throw new Error("Results not found"); // Now this error is thrown because you don't have results
}
} catch (error) {
console.error(e);
}
});
});
但是当我使用api/users/signin/ksds之类的东西时。它确实使用了notFound中间件,并给了我邮差中的错误。
因为您正在创建一个自定义错误并将其发送到节点默认错误处理程序,该处理程序为您完成工作,而邮递员会收到错误消息。
但在正文中,如果我使用了不正确的密码,它应该在邮递员控制台显示错误。但它所做的却给了我vscode控制台中的错误
但是,在本例中,您抛出了一个错误,它正在执行它的工作,并且您在控制台中看到了该错误。如果您不希望这种行为,请遵循上面使用的相同流程。
查看更多细节:如何处理Node.js中的错误?