res.json没有将我的错误消息发送给客户端吗? [英] res.json is not sending my error message to the client?

查看:177
本文介绍了res.json没有将我的错误消息发送给客户端吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个错误处理程序,可以根据发生的情况检索特定的错误消息.但是问题是,当我使用.catch()运行我的错误处理程序函数时,如果我登录到节点控制台,它将起作用,但是当我尝试通过res.json()将其发送给客户端时,它将仅发送状态代码,而不是我的错误处理程序的任何部分.

I have this error handler that retreives specific error messages based on what happens. But the thing is when I run my error handler function with .catch() it will work if i'm logging to the node console, but when i try send it to the client via res.json() it will only send the status code, not any part of my error handler.

function errorHandler(error){
  if (error.name === 'SequelizeValidationError') {
    const errors = error.errors.map(err => err.message);
    return errors;
  } else {
    throw error;
  }
}


router.post('/create', async(req, res) => {
     await Movie.create(req.body)
      .then(() => res.json("Movie Created"))
      .catch( err => res.status(401).json(errorHandler(err)) );
  });

这是我的错误处理程序代码和我正在谈论的路由.它可以在节点控制台中运行,但是就像我说的那样,它仅将状态401代码发送给客户端,而没有其他发送.如何将错误消息也发送到客户端?

This is my code for the error handler and the route i'm talking about. It works in the node console, but like I said it only sends the status 401 code to the client and nothing else. How can I get my error message send to the client as well?

谢谢!

推荐答案

因为它不等待errorHandler的结果.让他们等待. 试试这个.

Because its not waiting for result from errorHandler. Make them wait for it. Try this.

function errorHandler(error, cb){
  if (error.name === 'SequelizeValidationError') {
    const errors = error.errors.map(err => err.message);
     cb(errors);
  } else {
    throw error;
  }
}


router.post('/create', async(req, res) => {
     await Movie.create(req.body)
      .then(() => res.json("Movie Created"))
      .catch( err => {
              errorHandler(err, function(errors){
                   res.status(401).json(errors);
               });
      });
  })

或者您可以返回Promise并在errorHandler上等待.

Or you can return a Promise and await on errorHandler.

这篇关于res.json没有将我的错误消息发送给客户端吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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