javascript - 获取 html 错误 301,返回完全相同的链接

标签 javascript html node.js

我正在尝试使用 Node.js 应用程序获取 HTML 页面的内容。 我找到了这个代码:In Node.js / Express, how do I "download" a page and gets its HTML? (yojimbo 回答),这似乎运作良好。当我尝试启动代码时,我得到了 301 Moved Permanently 的 HTML 结果,但重定向链接与我发送的链接相同!

var util = require("util"),
    http = require("http");

var options = {
    host: "www.mylink.com",
    port: 80,
    path: "/folder/content.xml"
};

var content = "";   

var req = http.request(options, function(res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
        content += chunk;
    });

    res.on("end", function () {
        util.log(content);
    });
});

req.end();

返回结果是:

30 Jul 13:08:52 - <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<p>The document has moved <a href="http://mylink.com/folder/content.xml"<here</a>.</p>
<hr>
<adress>Apache/2.2.22 (Ubuntu) Server at www.mylink.com Port 80</adress>
</body></html>

它是永久移动到同一个地方还是只是服务器上的某种安全措施?或者我在代码中犯了错误? (但它适用于谷歌和我测试的所有其他网站)。

我怀疑是“.xml”导致了问题,因为我什至用pdf中的页面进行了测试,没有问题(只是一堆不可读的字符)。

与客户讨论后,我用另一种方式获取页面(直接下载),效果还可以。我仍然接受c.Pu.1的答案,但我仍然想知道为什么重定向链接与应用程序遵循的链接相同。

最佳答案

301 状态代码表示请求的资源已被移动,并且客户端必须执行重定向到响应的 Location header 中包含的链接。默认情况下,http 模块不遵循重定向(状态代码 3xx)。

您可以使用request模块,据说可以执行重定向。

Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.

要手动执行此操作,请从响应中读取 Location header ,并向该 URI 发起新请求。

var req = http.request(options, function(res) {
    res.setEncoding("utf8");
    if(res.statusCode === 301 || res.statusCode === 302) {
        var newRequestUri = res.headers.location;
        http.request({hostname: newRequestUri}, function(res) {
            //read response
        }
    }
    res.on("data", function (chunk) {
        content += chunk;
    });

    res.on("end", function () {
        util.log(content);
    });
});

关于javascript - 获取 html 错误 301,返回完全相同的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17945772/

相关文章:

javascript - Mongoose递归查询父引用

node.js - 进程替换 - Node.js child_process

javascript - Intellij IDEA 编辑器无法找到外部 javascript 库

javascript - 广播中的 ng-model 始终保持真实

html - css页脚总是在页面底部

javascript - Android 不安全 :tel: with phonegap application

node.js - Nodejs中的Mongodb upsert命令

javascript - 最小最大价格范围验证不适用于 jquery.validate.js

javascript - 带有dimple.js图表​​的嵌套JSON对象数据

javascript - 为什么是 `null >= 0 && null <= 0` 而不是 `null == 0` ?