首页 > 解决方案 > 如何使用 Express/got 代理/流式传输 HTTPS 请求?

问题描述

我正在尝试使用Express通过我的服务器代理 GitHub 用户头像并得到.

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

GotError:主机名/IP 与证书的替代名称不匹配:主机:localhost。不在证书的替代名称中: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)
    }
  }
})

标签: node.jsexpress

解决方案


最终使用getvsstream并且它有效。

话虽如此,我相信流媒体更有效,所以如果您知道如何使用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)
    }
  }
})

推荐阅读