【问题标题】:request.pipe() allow failing requestrequest.pipe() 允许失败的请求
【发布时间】:2019-11-14 13:41:48
【问题描述】:

我正在使用request.pipe() 转发我的丰富请求。 问题是它在管道请求成功时转发响应,但在请求失败时响应错误。我想要的是让管道响应返回的任何请求。例如,当它返回 404 时,然后将 404 响应传递给原始请求。

这就是我所拥有的

app.all('*', (req: Request, res: Response) => {
  req.headers.extraHeader = JSON.stringify(res.locals.infoFromMiddleware)

  req.pipe(request(`http://localhost:3000${req.url}`)).pipe(res)
})

我收到以下错误: UnhandledPromiseRejectionWarning: Error: Request failed with status code 404(或 400 / 500 / 等)

【问题讨论】:

  • 你得到什么错误?这可能与 express 在此方法之前调用您的错误中间件这一事实有关,这意味着在将响应通过管道传输到代理之前将其发回。
  • 我更新了问题

标签: node.js express proxy request


【解决方案1】:

大概是这样的

app.all('*', (req: Request, res: Response) => {
  req.headers.extraHeader = JSON.stringify(res.locals.infoFromMiddleware)

  req
   .pipe(request(`http://localhost:3000${req.url}`))
   .once('error', err => res.status(404).send(JSON.stringify(err)))
   .pipe(res)
})

【讨论】:

  • 但这不仅仅是处理 404。我希望代理传递响应而不考虑错误,并且还包括响应正文和标头。
猜你喜欢
  • 2023-04-02
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
相关资源
最近更新 更多