为什么当 API 返回 400 HTTP 状态代码时 NodeJS 会崩溃?

时间:2021-04-14 08:36:29

标签: node.js typescript http

我正在使用这个 API,一切都很好,直到我尝试了 POST 方法。

现在发生的情况是,当我尝试从邮递员发送数据时,NodeJS 应用程序崩溃,显示此错误:HTTPError: Response code 400 (Bad Request) 并指出该错误在 catch 部分被调用。

事情是这样的,当我直接向 API 直接发送 post 请求时(不是使用我的本地主机服务器),它返回 400: Bad request 和数据不正确的消息。现在,当我直接发送它时一切正常,但是当我尝试使用本地主机调用 API 时,它会引发该错误。

错误是从调用中抛出的:got.post(...) 使用了这个库: https://www.npmjs.com/package/got

是否有可能进行该调用并获得 400 响应而不会从调用中引发错误?

方法.ts

export const addReservation = async (postData: object) => {
  const url = API_URL + '/reservation';

  try {
    const response = await got.post(url, {
      json: { ...postData },
      responseType: 'json',
    });
    
    console.log(response.statusCode); //no success, jumps to the catch block
    return response.body;
  } catch (error) {
    throw new Error(error);
  }
};

reservation.ts

export const reservationHandler = async (req: Request, res: Response) => {
  let postData = req.body;

  let response = await addReservation(postData);
  return res.status(201).json(response); //if all is OK it will return 201, but if not 400
};

所以我尝试在 addReservation 中捕获状态代码但没有成功。我通过处理状态代码 400 或 201 的情况有了想法,但如果状态为 201,则仅继续 try 块,但如果状态为 400,它会使应用程序崩溃。

1 个答案:

答案 0 :(得分:0)

您必须在 throwHttpErrors 选项中将 got 设置为 false。

https://github.com/sindresorhus/got#throwhttperrors