【发布时间】:2019-12-13 14:31:57
【问题描述】:
我是 node.js 的新手
我在通过 https 请求获取 html 正文时遇到问题。我正在使用以下脚本:
var request = require('request');
var options = {
url: 'https://icobench.com/ieo',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
============================================
我也尝试通过以下代码获取页面:
const https = require('https');
var options = {
hostname: 'icobench.com',
port: 443,
path: '/ieo/',
method: 'GET'
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.end();
req.on('error', (e) => {
console.error(e);
});
但它会返回错误:
statusCode: 503
headers: { date: 'Mon, 16 Dec 2019 08:05:21 GMT',
'content-type': 'text/html; charset=UTF-8',
'transfer-encoding': 'chunked',
connection: 'close',
'set-cookie':
[ '__cfduid=de0d50bfceb3fee0883f10b9f6d1440341576483521; expires=Wed, 15-Jan-20 08:05:21 GMT; path=/; domain=.icobench.com; HttpOnly; Secure',
'PHPSESSID=tkt1clieuc55bq0ilvho2b0dr3; path=/' ],
expires: 'Thu, 19 Nov 1981 08:52:00 GMT',
'cache-control': 'no-store, no-cache, must-revalidate',
pragma: 'no-cache',
'x-frame-options': 'SAMEORIGIN',
'retry-after': '300',
'cf-cache-status': 'DYNAMIC',
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
'x-content-type-options': 'nosniff',
'expect-ct':
'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
server: 'cloudflare',
'cf-ray': '545f26d6cbcbbdb9-AMS' }
我应该在我的代码中进行哪些更改以获取 html 正文来解析它?
感谢您的回答。
【问题讨论】:
-
但是你实际上在哪里
requesting呢?request(options, callback)? -
哦,对不起。我没有包括函数调用。我在一分钟前更改了代码。
-
您需要等待结果。或者在回调函数中添加一些东西。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
使用另一个 http URL 效果很好。但是使用 https 会出现问题。
标签: html node.js https request