在node.js的Request中调用 "Request "范围外的变量。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在node.js的Request中调用 "Request "范围外的变量。相关的知识,希望对你有一定的参考价值。
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的新手,我想做一个实验性的Bot,我使用 "request "来发送一个 "Get "到我的网站,通过 "Php",它被保存在 "mysqli "数据库中。
但是,由于我已经得到了所需的数据,我无法访问它。我怎样才能从函数外访问'Request'的'body'?
请参考上面的代码
有什么办法可以在外面调用它吗,我可以更容易地管理我的代码
请注意:这只是真实代码的一个小快照,真实的代码有很多ifelse,循环和其他函数,把它变成括号下的括号会有点复杂。
谢谢你
所以请求函数是异步的,这意味着你调用了 request("http://...")
而node js会启动该函数,然后不等它完成就跳到下一行。所以如果你有。
request("http://example.com/index.php?username=username&password=password", function() {
console.log("1");
});
console.log("2");
你会看到 2
前登录 1
. 这就给我们带来了 request 的第二个参数的函数:回调函数。你传入了一个函数让request调用。一旦它完成了对你的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);
});
你需要访问体内的 范围 的回调函数。
以上是关于在node.js的Request中调用 "Request "范围外的变量。的主要内容,如果未能解决你的问题,请参考以下文章
Node.js Lambda 函数从 REST 调用将“响应无效”返回给 Alexa 服务模拟器
node.js:如何在 forEach 循环中使用异步调用实现路由方法?