在express控制器内进行axios调用时,如何返回状态?

s71maibg  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(495)

我不确定我是否正在设置express控制器以正确返回正确的响应。当端点被命中时,我想用axios调用地址服务并返回数据,或者在出错时返回响应。但是,如果找不到,则当前返回默认错误400,但响应状态仍为200。
这里是否有我遗漏的默认方法,或者这部分是正确的?
控制器

  1. const getAddressWithPostcode = async (params: Params) => {
  2. const { postCode, number } = params
  3. const addressUrl = `${URL}/${postCode}${number
  4. ? `/${number}?api-key=${API_KEY}`
  5. : `?api-key=${API_KEY}`}`
  6. try {
  7. const { data } = await axios.get(addressUrl)
  8. return data
  9. } catch (e) {
  10. // throw e
  11. const { response: { status, statusText } } = e
  12. return {
  13. service: 'Address service error',
  14. status,
  15. statusText,
  16. }
  17. }
  18. }
  19. const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
  20. const { params } = req
  21. await getAddressWithPostcode(params)
  22. .then((data) => {
  23. res.send(data).status(200)
  24. })
  25. .catch((e) => {
  26. console.log('e', e)
  27. next(e)
  28. })
  29. }

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

这里的一些方向是好的,可能是在express中使用async Wait的最佳实践,并且在中使用外部axios调用时返回错误。
... ...
更新:
更新了我的代码,作为对答案的回应,我稍微重构了我的代码。

  1. const getAddressWithPostcode = async (params: Params) => {
  2. const { postCode, number } = params
  3. const addressUrl = `${URL}/${postCode}${number
  4. ? `/${number}?api-keey=${API_KEY}`
  5. : `?api-key=${API_KEY}`}`
  6. try {
  7. const { data } = await axios.get(addressUrl)
  8. return data
  9. } catch (e) {
  10. // throw e
  11. const { response } = e
  12. return response
  13. }
  14. }
  15. const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
  16. const { params } = req
  17. await getAddressWithPostcode(params)
  18. .then((data) => {
  19. console.log('data', data)
  20. if (data.status !== 200) res.sendStatus(data.status)
  21. else {
  22. res.send(data)
  23. }
  24. })
  25. .catch(err => {
  26. console.log('err', err)
  27. next(err)
  28. })
  29. }
oyjwcjzk

oyjwcjzk1#

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

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

相关问题