gpt4 book ai didi

Node.js请求网页

转载 作者:搜寻专家 更新时间:2023-10-31 23:06:19 24 4
gpt4 key购买 nike

我需要连接到网页并返回页面的状态代码,我已经能够使用 http.request 实现,但是我需要请求的页面可能需要很长时间时间,有时是几分钟,所以我总是遇到 socket hang up 错误。

到目前为止,我正在使用以下代码:

var reqPage = function(urlString, cb) {
// Resolve the URL
var path = url.parse(urlString);
var req = http.request({
host: path.hostname,
path: path.pathname,
port: 80,
method: 'GET'
});
req.on('end', function() {
cb.call(this, res);
});
req.on('error', function(e) {
winston.error(e.message);
});
};

我需要做什么来确保我的应用程序仍然尝试连接到该页面,即使它需要几分钟?

最佳答案

使用 request模块并将超时选项设置为适当的值(以毫秒为单位)

var request = require('request')
var url = 'http://www.google.com' // input your url here

// use a timeout value of 10 seconds
var timeoutInMilliseconds = 10*1000
var opts = {
url: url,
timeout: timeoutInMilliseconds
}

request(opts, function (err, res, body) {
if (err) {
console.dir(err)
return
}
var statusCode = res.statusCode
console.log('status code: ' + statusCode)
})

关于Node.js请求网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15838623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com