【问题标题】:HTTP 200 (OK) returned instead of 301 (Moved Permanently)返回 HTTP 200(OK)而不是 301(永久移动)
【发布时间】:2021-06-16 18:54:45
【问题描述】:

此 URL 向 wget 和 curl 返回代码 301,但 node-fetch 报告的是 200:

# wget https://www.h24info.ma/feed
--2021-03-19 11:30:23--  https://www.h24info.ma/feed
Resolving www.h24info.ma (www.h24info.ma)... 104.21.39.120, 172.67.145.67, 2606:4700:3030::6815:2778, ...
Connecting to www.h24info.ma (www.h24info.ma)|104.21.39.120|:443... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
# curl -I https://www.h24info.ma/feed
HTTP/2 301

但是 fetch 返回 200(并且永远挂起):

fetch('https://www.h24info.ma/feed', {
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36',
  'accept': 'text/html,application/xhtml+xml'
}).then(function (res) {

  console.error('node-fetch status: %s', res.status);
});

node-fetch status: 200

我错过了什么吗? Fetch 应该返回 301,以便可以中止请求并处理错误。

software version
node-fetch 2.6.1
node v14.15.3
npm 7.6.0
Operating System Linux 4.9.0-15-amd64 #1 SMP Debian 4.9.258-1 (2021-03-08) x86_64 GNU/Linux

【问题讨论】:

    标签: node.js http-error node-fetch


    【解决方案1】:

    默认情况下fetch 透明地遵循重定向。也就是说,如果请求的 URL 返回 301/302 重定向响应代码,fetch 将自动向重定向 URL 发出另一个请求,您得到的响应将是来自第二个请求的响应。

    您可以通过提取选项对象中的redirect 字段配置此行为:

    fetch(URL, {
      redirect: 'manual' // do not follow redirects automatically
    })
    

    Check out the MDN docs for fetch 了解更多信息。

    Fetch 应该返回 301,以便可以中止请求并处理错误。

    301 状态并不是真正的错误,所以我认为fetch 的默认行为是正确的。在大多数情况下,您想要的是fetch 来请求指定的资源,而不管它实际在哪里。为此,如果服务器告诉fetch 在别处寻找资源,它会。

    【讨论】:

      猜你喜欢
      • 2016-07-04
      • 2018-09-11
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 2012-07-10
      相关资源
      最近更新 更多