【问题标题】:How can I get the original request URL in the response callback?如何在响应回调中获取原始请求 URL?
【发布时间】:2019-10-10 16:48:14
【问题描述】:

我有一个这样的循环:

var req;

for (var i=0; i<sites.length; i++) {
    req = https.get(sites[i], handleRequest);
    req.on('error', handleError);
}

对于每个被请求的网站,回调 (handleRequest) 异步运行。

但是,handleRequest 中唯一的参数似乎是“响应”。 当回调运行时,循环已经完成,那么如何跟踪这个响应是针对哪个网站的,以便我可以进行相应的处理呢?

【问题讨论】:

  • 响应没有说明它来自哪里?我正在查看the documentation,但它没有解释响应对象。从代码示例中,我可以看到它有一个 headers 属性,所以我希望它在那里有原始 URL。
  • 不。标头只显示如下内容: { "date": "Thu, 10 Oct 2019 16:30:08 GMT", "server": "Apache", "connection": "close", "transfer-encoding": "chunked ", "内容类型": "text/html; charset=UTF-8" }
  • 好吧……很奇怪。无论如何,我想我有一个解决方案,那么。
  • 带上它! :) 非常感谢。

标签: node.js http https


【解决方案1】:

您可以更改您的 handleRequest 以采用两个参数 - url 是其中的第一个。有了它,您可以通过Function#bind 来partially apply 函数,因此在调用时设置 url 参数,但您仍将等待第二个参数。

let sites = [
  "https://example.com",
  "https://example.net",
  "https://example.org"
];

function handleRequest(url, res) {
  console.log("handling:", url);
  
  /* handling code */
}

//minimalistic dummy HTTP module that responds after 1 second
let https = {
  get: handler => setTimeout(handler, 1000)
}

for (var i=0; i < sites.length; i++) {
    let url = sites[i];
    https.get(handleRequest.bind(this, url)) //partially apply handleRequest
}

您可以通过currying 获得类似的结果 - 而不是有两个参数,首先取一个,然后返回一个接受另一个的函数。调用时(在我看来)它会导致更好的语法:

let sites = [
  "https://example.com",
  "https://example.net",
  "https://example.org"
];

function handleRequest(url) {
  return function actualHandler(res) {
    console.log("handling:", url);
  
    /* handling code */
  }
}

//minimalistic dummy HTTP module that responds after 1 second
let https = {
  get: handler => setTimeout(handler, 1000)
}

for (var i=0; i < sites.length; i++) {
    let url = sites[i];
    https.get(handleRequest(url))
}

【讨论】:

    猜你喜欢
    • 2012-07-11
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2014-02-24
    • 2020-11-29
    • 2022-06-17
    • 1970-01-01
    相关资源
    最近更新 更多