【问题标题】:Making an axios call inside my express controller, how do I return the status?在我的 express 控制器中进行 axios 调用,如何返回状态?
【发布时间】:2021-09-21 12:44:54
【问题描述】:

我不确定我是否设置了我的快速控制器以正确返回正确的响应。当端点被命中时,我想用 axios 调用地址服务并返回数据,或者如果出错则返回响应。但是,目前如果找不到则返回默认错误400,但响应状态仍然是200。

这里是否有我遗漏的默认方法,或者这部分正确?

控制器

const getAddressWithPostcode = async (params: Params) => {
  const { postCode, number } = params

  const addressUrl = `${URL}/${postCode}${number
    ? `/${number}?api-key=${API_KEY}`
    : `?api-key=${API_KEY}`}`

  try {
    const { data } = await axios.get(addressUrl)
    return data
  } catch (e) {
    // throw e
    const { response: { status, statusText } } = e
    return {
      service: 'Address service error',
      status,
      statusText,
    }
  }
}

const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
  const { params } = req

  await getAddressWithPostcode(params)
    .then((data) => {
      res.send(data).status(200)
    })
    .catch((e) => {
      console.log('e', e)
      next(e)
    })
}

如果我发送一个狡猾的请求(使用邮递员),我会得到响应状态 200,但返回的数据是带有状态和文本的对象。我想将此作为我的默认响应,而不是返回具有这些属性的对象。 (见下图)。

这里只是一些方向会很好,可能是在 express 中使用 async await 和在内部使用外部 axios 调用时返回错误的最佳实践。

... ...

更新:

为此更新了我的代码,作为对答案的回应,我稍微重构了我的代码。

const getAddressWithPostcode = async (params: Params) => {
  const { postCode, number } = params

  const addressUrl = `${URL}/${postCode}${number
    ? `/${number}?api-keey=${API_KEY}`
    : `?api-key=${API_KEY}`}`

  try {
    const { data } = await axios.get(addressUrl)
    return data
  } catch (e) {
    // throw e
    const { response } = e
    return response
  }

}

const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
  const { params } = req

  await getAddressWithPostcode(params)
    .then((data) => {
      console.log('data', data)
      if (data.status !== 200) res.sendStatus(data.status)
      else {
        res.send(data)
      }
    })
    .catch(err => {
      console.log('err', err)
      next(err)
    })
}

【问题讨论】:

    标签: javascript node.js typescript express error-handling


    【解决方案1】:

    如果您想发送与从 axios 调用中获得的相同的 http 响应代码,只需在控制器中更改以下一行代码即可。

    // Every time send same http status code 200
    res.send(data).status(200)
    
    // Send same http status code as returned by axios request
    res.send(data).status(data.status)
    

    【讨论】:

    • 谢谢,这已经奏效了——我认为这是常见的做法?然后 catch 应该返回任何网络错误而不是 axios 错误?
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 2017-02-17
    • 2016-04-22
    • 2020-08-13
    • 2019-12-25
    • 1970-01-01
    • 2014-04-27
    • 2010-11-28
    相关资源
    最近更新 更多