在尝试记录此响应时,为什么我会“未定义”?

时间:2018-05-10 18:33:10

标签: javascript get

我正在尝试使用tempToFahrenheit: function(tempInC){ tempInF = (tempInC*1.8)+32; return tempInF; }, getTextWeatherUsingStationUsingRequest: function(theStation){ const http = require("http"); const https = require("https"); // theURL = 'https://api.weather.gov/stations/' + theStation + '/observations/current'; thePath = '/stations/' + theStation + '/observations/current'; function requestTheData(){ var returnedJSON; var options = { protocol: "https:", hostname: "api.weather.gov", path: thePath, method: "GET", headers: { 'Accept' : 'application/json', 'Content-Type': 'application/json', 'User-Agent' : 'MY-TEST-UA' } }; var req= https.request(options); var theData = ''; req.on("response", function(res){ console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); theData += chunk; }); res.on('end', () => { console.log('No more data in response.'); returnedJSON = JSON.parse(theData); console.log(returnedJSON.id); // Why can't ot find temptoFahrenheit theTemp = Math.round( tempToFahrenheit(returnedJSON.properties.temperature.value) ) windSpeed = Math.round(returnedJSON.properties.windSpeed.value); pressure = returnedJSON.properties.barometricPressure.value; 函数创建一个带有URL的对象,创建get请求,然后返回GET。但是,使用我当前的代码,每当我尝试记录它时,我都会得到responseText

undefined

编辑:在这个问题被标记为重复后,我会查看我'重复'的问题并解决了我的问题,但我不明白为什么var HttpRequest = function() { this.get = function(url, callback) { var httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = function() { if(httpRequest.readyState == 4 && httpRequest.status == 200) { callback = httpRequest.responseText; } }; httpRequest.open("GET", url, true); httpRequest.send(null); return callback; }; }; var request = new HttpRequest(); var response = request.get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=BTC,USD"); console.log(response); 无效。我已经将我的代码更新为应该工作的东西,但是没有。回调函数是在某些事情完成后调用的函数,但为什么return不能代替它?

更新的代码:     var HttpRequest = function(){       this.get = function(url){

return

0 个答案:

没有答案