关于http模块的request方法 timeout 超时问题~~~
发布于 20 天前 作者 ipengyo 318 次浏览 来自 问答

6.2的文档: https://nodejs.org/dist/v6.2.0/docs/api/http.html#http_http_request_options_callback

里面没有timeout这个配置项

8.2的文档: https://nodejs.org/api/http.html#http_http_request_options_callback

image.png

我想请问一下 这个timeout 配置是啥时候加进来的。

现在要处理http模块 request 返回结果超时,用什么办法比较好(我目前用的6.2版本的)

5 回复
request.setTimeout(timeout[, callback])#

Added in: v0.5.9
timeout <number> Milliseconds before a request is considered to be timed out.
callback <Function> Optional function to be called when a timeout occurs. Same as binding to the timeout event.
Once a socket is assigned to this request and is connected socket.setTimeout() will be called.

Returns request.

这个貌似是正解? 请大家帮忙参考~~~

可以参考下 npm 上 request 模块关于 timeout 的实现源代码, 他们应该是使用 req.setTimeout 手动实现的

Github 链接在这里: https://github.com/request/request/blob/b12a6245d9acdb1e13c6486d427801e123fdafae/request.js#L742

找到了这个timeout 是啥时候加进去的: https://github.com/nodejs/node/pull/8101/files

分享一下我的的代码把:

function post(url, data, cb) {

    let parsed_url = parse_url(url);

    let protocal = (parsed_url.protocol == "https:") ? https : http;
    console.log('post url:' + url);

    let req = protocal.request({
        host: parsed_url.hostname,
        port: parsed_url.port,
        path: parsed_url.path,
        method: 'POST',
        rejectUnauthorized: false,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    }, function(res) {
        let chunks = '';
        res.setEncoding('utf8');
        res.on('data', (chunk)=>{
            chunks += chunk;
        });
        res.on('end', ()=>{
            if(!cb) {
                return ;
            }
            try{
                console.log('response:' + chunks + ' url:' + url);
                let response = JSON.parse(chunks);
                cb(null, response);
            } catch(e) {
                cb(e); 
            }
        });
    });
    req.setTimeout(timenum, function(){
        var e = new Error('http request timeout url:' + url);
        e.code = 'ESOCKETTIMEDOUT';
        e.connect = false;
        this.abort(); //结束当前请求 https://nodejs.org/api/http.html#http_request_abort
        this.emit('error', e);
    }.bind(req));
    req.on('error', function(error) {
      if(!cb) {
        console.error(error);
        return ;
      }
      cb(error);
      cb = null;
    });
    req.write(querystring.stringify(data));
    req.end();
}
回到顶部