本文介绍了node.js:如何停止已经启动的http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用与node.js发出http请求。
我们希望在用户决定时让用户有机会中止请求。这意味着我们必须从请求函数外部触发abort()。也许我们可以从函数内部检查外部变量。
(我们已经尝试在请求开始后将超时设置为零,这不起作用。)
也许我们将变量请求设置为null。你知道更好的方法吗?

We use request to make http requests with node.js.We would like to give the user an opportunity to abort the request when he decides. That means we have to trigger the abort() from outside the request function. Maybe we can check an outside variable from inside the function.(We already tried to set the timeout to zero after the request started, that doesn't work.)Maybe we set the variable request to null. Do you know a better way to do this?

这里是一个示例代码,显示我们正在讨论的请求类型:

here is example code to show what kind of request we are talking about:

app.js:

var http = require('http');
var request = require("request");

http.createServer().listen(1337, "127.0.0.1");

request({uri: 'http://stackoverflow.com'  }, function (error, response, body) {
    console.log('url requested ') ;
    if (!error){
        console.log(body);
    }
    else
    {
        console.log(error);
    }
});


推荐答案

请求函数返回一个请求对象。只需在那上面调用 abort()

The request function returns a request object. Just call abort() on that?

var r = request({uri: 'http://stackoverflow.com'  }, function (error, response, body) {
    console.log('url requested ') ;
    if (!error){
        console.log(body);
    }
    else
    {
        console.log(error);
    }
});

r.abort();

这篇关于node.js:如何停止已经启动的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:33