[英]How to export a variable made by a request in node.js
In my first script, I execute a function which takes the HTML from a webpage. 在第一个脚本中,我执行一个函数,该函数从网页获取HTML。 I'd like to use this HTML in another script, but the return always comes back as undefined... 我想在另一个脚本中使用此HTML,但是返回总是以未定义的形式返回...
var html;
exports.html = html;
exports.makeRequest = function makeRequest(url){
request({
url: url,
auth: {
user: '*****',
pass: '*****'
},
rejectUnauthorized: false,
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
html = body.toString();
exports.html = html;
}
});
}
I've tried making the variable a global, but to no avail. 我试过将变量设置为全局变量,但无济于事。
This is the code I'm using to call the html. 这是我用来调用html的代码。
var myRequests = require('./Request');
console.log(myRequests.makeRequest(url))
console.log(myRequests.html);
Sending a request is an async operation. 发送请求是异步操作。 That means you need to wait until the request is finished then retrieve the data via a callback. 这意味着您需要等待请求完成,然后通过回调检索数据。
exports.makeRequest = function makeRequest(url, cb) {
request({
url: url,
auth: {
user: '*****',
pass: '*****'
},
rejectUnauthorized: false,
}, function(error, response, body) {
if (error) {
return cb(er);
}
if (response.statusCode !== 200) {
return cb(new Error('Request failed with code ' + response.statusCode));
}
cb(null, body.toString());
});
}
//usage
var myRequests = require('./Request');
myRequests.makeRequest(url, function(er, html) {
if (er) {
return console.log(er);
}
console.log(html);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.