以编程方式获取XHR内容



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

在使用Safari中的Web检查器时,我注意到我想要的数据在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);

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

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

网络检查员1 屏幕截图

屏幕截图web检查器2

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);
});
});

最新更新