node.js - 如何使用 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)
}
}
})
解决方案
最终使用get
vsstream
并且它有效。
话虽如此,我相信流媒体更有效,所以如果您知道如何使用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)
}
}
})
推荐阅读
- python - tkinter 中的标题栏菜单
- python - 为什么 datetime, timedelta 给出不同的值
- javascript - 根据选定的下拉列表填充输入字段值
- python - 如何将 Discord Bot 连接到语音频道?
- python - Win32com.client.dispatch Python 调用等价于 C 或 C++
- python - 尝试探索由列表组成的列表时,“列表索引必须是整数或切片,而不是列表”
- r - 在 testthat 中捕获错误但不要停止循环 - 测试
- delphi - 如何将数据库中的数据分配给 dxlooktreeview?
- format - 如何使用乳胶将我的签名放在文档的右侧?**乳胶**
- android - Spinner - 如何获得价值?安卓工作室