Node.js将HTTP响应转换为变量
我试图得到http请求对我的可变温度的响应,但它不起作用,我已经尝试过回调,但我不是很熟悉它,所以我现在无法解决我的问题。也许有人有主意 感谢并致以最良好的祝愿:-Node.js将HTTP响应转换为变量,node.js,http,variables,httprequest,global,Node.js,Http,Variables,Httprequest,Global,我试图得到http请求对我的可变温度的响应,但它不起作用,我已经尝试过回调,但我不是很熟悉它,所以我现在无法解决我的问题。也许有人有主意 感谢并致以最良好的祝愿:- var temperature = ''; http.get(url, function(res) { //console.log("Got response: " + res.statusCode); var bodyarr = []; res.on('data', function(chunk){
var temperature = '';
http.get(url, function(res) {
//console.log("Got response: " + res.statusCode);
var bodyarr = [];
res.on('data', function(chunk){
bodyarr.push(chunk);
});
res.on('end', function(){
//console.log(*/bodyarr.join('').toString());
temperature = bodyarr;
});
enter code here
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
console.log(temperature);
这里的问题是关于异步性的;此时未定义温度对象,因为在请求完成之前调用了log方法。因为它是异步的,所以使用;它将回调作为参数,如果要获得完整的响应,请将其传递给response.end:
//The url for example is 'www.random.org/temperatures/?min=1&max=100'
var options = {
host: 'www.random.org',
path: '/temperatures/?min=1&max=100'
};
var temperature = '';
var http = require('http');
callback = function(res) {
var bodyarr = [];
res.on('data', function (chunk) {
bodyarr.push(chunk);
});
res.on('end', function () {
console.log(req.data);
console.log(bodyarr);
temperature = bodyarr.join();
});
}
var req = http.request(options, callback).end();
你测试代码了吗?您在哪里定义了温度变量?很抱歉,我已经更新了答案,将温度对象包括在内,这没有经过测试,只是一个基于的建议,这是相同的结果,通过console.log的输出有效,但是温度是空的:-/它是空的,因为您试图将数组bodyarr分配给字符串温度。使用join方法将数组的元素连接成字符串,然后将其分配给温度变量,或者简单地将温度变量更改为数组。不,仍然是相同的结果:-我有相同的问题,你解决了吗?