首页 > 解决方案 > 在请求 npm 中调用“请求”范围之外的变量。在 node.js

问题描述

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、循环和其他函数。将其放入括号下的括号会有点复杂。

谢谢

标签: node.jshttprequest-npm

解决方案


所以请求函数是异步的,这意味着你调用request("http://...")并且 node 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的。

Request 接受您传入的函数并注入参数:错误、响应和正文,您可以在回调函数中使用它们。

因为您在这里通过回调函数处理请求,该回调函数被异步调用,所以您只能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);
});

您需要在回调函数的范围内访问正文。


推荐阅读