【问题标题】:How to proxy/stream HTTPS request using Express/got?如何使用 Express/got 代理/流式传输 HTTPS 请求?
【发布时间】:2020-06-10 10:01:55
【问题描述】:

我正在尝试使用 Expressgot 通过我的服务器代理 GitHub 用户头像。

没有rejectUnauthorized: false,以下代码块返回错误:

GotError:主机名/IP 与证书的替代名称不匹配:主机: 本地主机。不在证书的替代名称中:DNS:www.github.com, DNS:.github.com, DNS:github.com, DNS:.github.io, DNS:github.io, DNS:*.githubusercontent.com, DNS:githubusercontent.com

使用rejectUnauthorized: false,返回错误:

HTTPError:响应代码 404(未找到)

我做错了什么?

const server = express()
server.get("/api/github/:username", async (req, res) => {
  if (!req.params.username) {
    res.sendStatus(400)
  } else {
    try {
      const stream = got.stream(
        `https://avatars.githubusercontent.com/${req.params.username}?size=64`,
        {
          rejectUnauthorized: false,
        }
      )
      stream.on("error", error => {
        res.sendStatus(500)
      })
      req.pipe(stream).pipe(res)
    } catch (error) {
      res.sendStatus(400)
    }
  }
})

【问题讨论】:

  • 一旦我遇到与 axios 相同的问题,解决方案是在配置对象中指定主机,在您的情况下将是 'avatars.githubusercontent.com'
  • 感谢您的反馈。刚刚尝试添加hosthostname 并出现同样的错误。

标签: node.js express


【解决方案1】:

最终使用 get vs stream 并且它有效。

话虽如此,我相信流式传输更有效,所以如果您知道如何使用stream 达到相同的结果,请提交反馈。

server.get("/api/github/:username", async (req, res) => {
  if (!req.params.username) {
    res.sendStatus(400)
  } else {
    try {
      const response = await got(
        `https://avatars.githubusercontent.com/${req.params.username}`,
        { responseType: "buffer" }
      )
      res.set({
        "Content-Length": response.headers["content-length"],
        "Content-Type": response.headers["content-type"],
      })
      res.send(response.body)
    } catch (error) {
      res.sendStatus(500)
    }
  }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 2017-06-27
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多