![](/img/trans.png)
[英]Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request?
[英]How can I turn a Node.js http.IncomingMessage into a Fetch Request object?
我正在尝试使用 eBay API。 这是一个只需要在本地运行的小型个人项目,虽然我知道 C#,但我对 Javascript 更满意,所以我正在寻找在 JS 中完成这项工作的方法。
我发现这个具有浏览器支持的看起来很有前途的 eBay 节点 API 。 浏览器支持是我正在寻找的东西,但它也说
在浏览器中使用 API 需要代理服务器。
他们为作为 Cloudflare 工作者 的代理服务器提供了一个示例文件。
我正在尝试使用基本的 Node HTTP 服务器将其转换为可以在 Node 本地运行的内容。 我一直在关注它并且到目前为止做得很好,想出了访问标题和检查它们的不同方法等,但现在我正处于代理服务器向 eBay 发出代理请求的地步蜜蜂。 示例文件的设置方式似乎 Cloudflare 工作人员拦截了 HTTP 请求,并默认将其视为 Fetch Request
。 因此,当它传递请求时,它只是克隆它(但是用“清理”的标头替换标头):
// "recHeaders" is an object that is _most_ of the original
// request headers, with a few cleaned out, and "fetchUrl"
// is the true intended URL to query at eBay
const newReq = new Request(event.request, {
"headers": recHeaders
});
const response = await fetch(encodeURI(fetchUrl), newReq);
问题是我没有要克隆的获取Request
- 因为我正在运行节点 HTTP 服务器,所以示例代码中的event.request
对我来说是http.IncomingMessage
。
那么我怎样才能把它变成一个 Fetch Request
呢? 我猜至少消息正文中有一些东西需要传递,如果不是我什至不知道的其他属性...
I don't mind doing the work, ie reading the stream to pull out the body, and then putting that into the Request
object somehow (or do I even need to do that? Can I just pipe the stream from the IncomingMessage
directly into a以某种方式Request
?),但是除了正文之外,我还需要确保从IncomingMessage
中获取到Request
吗?
如何将 Node http.IncomingMessage
转换为 Fetch Request
并确保包含所有相关部分?
我制作了一个简单的 function 进行转换。
const convertIncomingMessageToRequest = (req: ExpressRequest): Request => {
var headers = new Headers();
for (var key in req.headers) {
if (req.headers[key]) headers.append(key, req.headers[key] as string);
}
let request = new Request(req.url, {
method: req.method,
body: req.method === 'POST' ? req.body : null,
headers,
})
return request
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.