node.js - 在请求 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、循环和其他函数。将其放入括号下的括号会有点复杂。
谢谢
解决方案
所以请求函数是异步的,这意味着你调用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);
});
您需要在回调函数的范围内访问正文。
推荐阅读
- android - 将资产中的 index.html 加载到 WebView 中,但找不到 index.html 中引用的其他文件
- javascript - try-catch 块是使用“in”运算符的可靠方法吗?
- c# - 瀑布对话框中的 C# bot V4 文本提示
- django - 我如何存储锦标赛排名
- javascript - 第二次单击按钮没有获得新的表单字段值
- javascript - 从 HTML 中清理/去除 Javascript
- python - 如何在python中获得两个平坦信号的精确相关因子?
- c - 如何设置多个指针?
- django - Django ModelForm - 以有效的形式访问自定义字段
- python - 我想在表中使用 python 在 spark 中添加某个 url 链接作为新列