簡體   English   中英

如何將 Node.js http.IncomingMessage 轉換為獲取請求 object?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM