var request = require('request');
request("http://example.com/index.php?username=username&password=password, function (error, response, body) {
var n1 = body.search('<user>');
var n2 = body.search('</user>');
var final = body.slice(n1+6, n2);
//it is working perfectly here.
final10 = final;
});
//The problem is that i can not call the "body" or variable "Final10" outside the Scope.
var final10=request.body
嗨, 我是Node JS的新手。 我正在尝试做一个实验机器人。我正在使用“请求”将“获取”发送到我的网站。通过“ Php”在那里,它被保存在“ Mysqli”数据库中。
一切正常,我得到了结果。 但是,由于我已获得所需的数据,因此无法访问它。 我如何从函数外部访问“请求”的“正文”?
请参考上面的代码
有什么办法可以在它外面调用它?我可以更轻松地管理我的代码
请注意:这只是真实代码中的一点点代码。真正的代码有很多if / else,循环和其他功能。 将其放入支架下面的支架将有点复杂。
谢谢
答案 0 :(得分:0)
因此,请求函数是异步的,这意味着您调用request("http://...")
,然后节点js触发该函数,然后跳至下一行而不等待其结束。因此,如果您有:
request("http://example.com/index.php?username=username&password=password", function() {
console.log("1");
});
console.log("2");
您会看到2
在1
之前被记录。这使我们进入了请求的第二个参数函数:回调函数。您正在传递一个用于请求调用的函数,一旦它完成了对您的url的api请求。因此,如果我们将以上示例更改为:
request("http://example.com/index.php?username=username&password=password", function() {
console.log("1");
console.log("2");
});
您会看到1
在2
之前被记录。
请求采用您传入的函数,并注入参数:错误,响应和正文,您可以在回调函数中使用这些参数。
由于您正在通过此处的回调函数处理请求(该请求被异步调用),因此只能在回调函数中使用body
。
request("http://example.com/index.php?username=username&password=password", function(error, response, body) {
// do something with the response body
console.log("Logging the response body", body);
});
您需要在回调函数的 scope 中访问正文。