在 nodeJS 中查找请求将被重定向到的最终 URL?

时间:2021-04-26 18:47:21

标签: node.js request response

我有以下网址:

https://forecast.weather.gov/zipcity.php?inputstring=95014

我想知道它将重定向到哪个 URL。在这个例子中是:

https://forecast.weather.gov/MapClick.php?CityName=Cupertino&state=CA&site=MTR&lat=37.3042&lon=-122.095

我尝试了多种解决方案,例如:

res.headers.location

res.headers.get('location')

但它们似乎都不起作用。我知道 URL 会重定向,因为我可以在 curlgoogle-chrome 中成功重定向。这是我正在运行的代码:

https.get('https://forecast.weather.gov/zipcity.php?inputstring=95014', res => console.log(res.headers.location))

当我在 curl 中运行时,我运行了以下内容:

curl -Ls -o /dev/null -w %{url_effective} http://forecast.weather.gov/zipcity.php?inputstring=95014

并得到所需的输出:

http://forecast.weather.gov/MapClick.php?CityName=Cupertino&state=CA&site=MTR&lat=37.3042&lon=-122.095

当我运行 curl 时:

$ curl -I https://forecast.weather.gov/zipcity.php?inputstring=95014
HTTP/2 302
server: Apache
x-nids-serverid: www1.mo
location: https://forecast.weather.gov/MapClick.php?CityName=Cupertino&state=CA&site=MTR&lat=37.3042&lon=-122.095
x-ua-compatible: IE=Edge
access-control-allow-origin: *
content-type: text/html; charset=UTF-8
content-length: 0
cache-control: max-age=722
expires: Mon, 26 Apr 2021 19:28:03 GMT
date: Mon, 26 Apr 2021 19:16:01 GMT
strict-transport-security: max-age=31536000 ; includeSubDomains ; preload

如您所见,此处存在多个标题,但在 nodejs 的结果中不存在:

{
  server: 'AkamaiGHost',
  'mime-version': '1.0',
  'content-type': 'text/html',
  'content-length': '288',
  expires: 'Mon, 26 Apr 2021 19:21:50 GMT',
  date: 'Mon, 26 Apr 2021 19:21:50 GMT',
  connection: 'close',
  'strict-transport-security': 'max-age=31536000 ; includeSubDomains ; preload'
}

我想坚持使用 http 模块。

0 个答案:

没有答案