【问题标题】:Nodejs request module - how can I cancel the request?Nodejs 请求模块 - 我如何取消请求?
【发布时间】:2021-03-10 14:31:14
【问题描述】:

我正在使用众所周知的请求模块 (https://github.com/request/request) 来请求一些页面,然后我进行了一些计算并为用户构建了响应代码。

问题是,有时我会收到正确的代码 (200),但数据(某种安全措施?)会永远发送 - 请求不会停止。在“不活动”一段时间后如何杀死它?

var requestOptions =
{
    url : url,
    timeout : 10000, //// here we set the request timeout - 10 seconds
    headers : {'we can also set some headers' : 'sometimes the pages require a headers - there is no proper responce without those'}
};

var ourRequest = request(requestOptions, function(err, resp, body)
{
    if (err || resp.statusCode >= 400) // OR just - (err || resp.statusCode !== 200)
    {
        console.log(err.connect);
        if (resp)
        {
            console.log('ERROR at last there is response (code: ' + resp.statusCode + ')\n');
        }
        else
        {
            if ((err.code === 'ETIMEDOUT') && (err.connect === true))
            {
                //// when there's a timeout and connect is true, we're meeting the conditions described for the timeout option where the OS governs
                console.log('REQUEST TIMEOUT - SYSTEM FAULT!');
            }
            else if ((err.code === 'ESOCKETTIMEDOUT') || (err.code === 'ETIMEDOUT'))
            {
                console.log('REQUEST TIMEOUT - NODE EXPRESS/REQUEST FAULT!');
            }
            console.log('ERROR you cant ge the body of the page...');
        }
    }
    if (resp.statusCode >= 300 && resp.statusCode < 400)
    {
        console.log('page REDIRECT');
    }
    if (!err && resp.statusCode == 200)
    {
        console.log('ok, we get the body, lets do something with it');
        console.log('some async code example to send part of the data to other servers, etc.');
    }
});

当我从中获取数据时,它是一个内部服务器 - 它有时在线,有时完全离线,因此我发现某些页面具有类似的“功能”,例如验证器。作为一个 url 设置一些页面并在其前面添加“https://validator.w3.org/nu/?doc=”,发出一些请求以查看有时它会挂起,并且超时对它们不起作用(可能导致接收正确的状态代码)。

如何在 10 秒后终止请求,即使它收到正确的状态码?感谢您对此主题的任何想法。

【问题讨论】:

    标签: node.js module request


    【解决方案1】:

    试试这个:

    resp.request.abort();

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 2018-05-04
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多