当前位置: 首页 > 知识库问答 >
问题:

Postman并没有在控制台中显示错误,而是在nodejs、express中停止服务器

姬国安
2023-03-14

我将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 };

在这里,我尝试使用NotFoundErrorHandler作为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);

我该怎么解决这个?所以,这也将帮助我在前端显示错误。

共有1个答案

慕容康安
2023-03-14

当您得到空结果时,就会出现这种错误。您应该首先检查结果的长度,然后对其使用属性或索引。

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中的错误?

 类似资料:
  • 问题内容: 如何停止VS2010在附加到项目的.sql文件中显示错误?我根本不想检查它们,只需C#代码即可。这些文件用作资源,“构建操作”设置为“内容”。我想保留.sql扩展名以进行语法着色。 问候, 问题答案: 看来您的问题已在这里得到回答: Visual Studio 2010 取消选中“启用IntelliSense”。 Visual Studio 2012和2013 取消选中“下划线错误”

  • 当然,对于GUI,除非运行我上面提到的命令,否则不会加载控制台,所以如果您有很多打印语句,它是否仍然影响程序的速度,它们是否仍然打印?(即使认为没有显示终端/控制台)

  • 问题内容: 是否可以通过JavaScript检查文件/页面是否存在,但阻止40​​4错误在控制台中显示? 问题答案: 似乎答案是:否。除非您启动对服务器端脚本的调用以检查文件是否存在,否则无法避免在控制台中出现404错误。

  • 我正在尝试执行具有te API的注册方法:http://localhost:100/api/v1/registration/connect当我运行前端和后端并检查源代码时,我收到一个内部服务器错误500内部服务器错误500 关于这一点,我检查了Spring Tools Suite控制台以检查问题所在,但没有发现任何错误。我需要查看控制台中的错误以找出问题所在。这是我收到错误的方法: 这是控制器方法

  • 我想停止在spark Shell上出现的各种消息。 为了停止这些消息,我尝试编辑文件。