【问题标题】:Programmatically get XHR content以编程方式获取 XHR 内容
【发布时间】:2020-04-17 04:51:24
【问题描述】:

我想以编程方式访问特定的 URL 内容 (MyURL/more_videos)。

在使用 Safari 中的 Web Inspector 时,我注意到我想要的数据位于 XHRs 文件夹中。在谷歌上搜索了 XHR 之后,我用 node.js 尝试了一些代码,但没有成功。

这是我在https://stackoverflow.com/a/32860099/8726869 找到的:

function readBody(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readBody(xhr));
    }
}
xhr.open('GET', ‘MyURL/more_videos', true);
xhr.send(null);

尽管如此,我没有得到任何控制台,既没有错误也没有响应。

我附上了一些网络检查器的屏幕截图:

Screenshot web inspector 1

Screenshot web inspector 2

【问题讨论】:

    标签: javascript node.js xml xmlhttprequest


    【解决方案1】:

    XMLHttpRequest 在浏览器中用于获取 URL。在 node.js 中,您应该使用 node.js http 库 (docs)。这是一个简单的例子:

    var http = require('http');
    
    http.get({
        host: 'httpbin.org',
        path: '/get'
    }, response => {
        let body = "";
        response.on('data', d => {
            body += d;
        });
        response.on('end', function() {
            console.log(body);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2013-02-25
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 2015-06-30
      相关资源
      最近更新 更多