javascript node.js:如何停止已经启动的 http 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15747632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js: how to stop an already started http request
提问by Michael Moeller
We use requestto 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?
我们使用request来通过 node.js 发出 http 请求。我们希望让用户有机会在他决定时中止请求。这意味着我们必须从请求函数外部触发 abort()。也许我们可以从函数内部检查外部变量。(我们已经尝试在请求开始后将超时设置为零,这不起作用。)也许我们将变量 request 设置为 null。你知道一个更好的方法来做到这一点吗?
here is example code to show what kind of request we are talking about:
这是示例代码,用于显示我们正在谈论的请求类型:
app.js:
应用程序.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);
}
});
回答by Jason Harwig
The request function returns a request object. Just call abort()
on that?
request 函数返回一个请求对象。就abort()
这么叫?
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();