返回了HTTP 200(OK),而不是301(已永久移动)



此URL向wgetcurl返回代码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,以便可以中止请求并处理错误。

版本
软件
节点获取2.6.1
节点v14.15.3
npm7.6.0
操作系统Linux 4.9.0-15-amd64#1 SMP Debian 4.9.258-1(2021-03-08(x86_64 GNU/Linux

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

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

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

查看fetch的MDN文档以了解更多信息。

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

301状态实际上并不是一个错误,所以在我看来fetch的默认行为是正确的。在大多数情况下,您希望fetch请求指定的资源,而不管它实际在哪里。为此,如果服务器告诉fetch在其他地方查找资源,它会的。

最新更新