2016-11-21 3 views
-1

Ich bin derzeit die Code-Api json returns "undefined"

const request = require('request') 
const apiKey = 'XXXXXXXXXXXXXX' 

var dat; 
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx' 
let qs = { 
    q: '-34.48,150.92', 
    format: 'json', 
    apiKey 
} 
request({ url, qs }, (err, response, body) => { 
    if (err) 
     return console.error(err) 
    if (response.statusCode != 200) 
     return console.error('status code is', response.statusCode) 
    body = JSON.parse(body) 
    dat = body.data.hourly[0].tempC 


}) 
console.log(dat); 

läuft und ich bin eine Antwort von 15 erwartet, als ich die API bin Referenzierung, die

{ 
"data": { 
    "request": [], 
    "weather": [{ 
     "date": "2016-11-20", 
     "astronomy": [], 
     "maxtempC": "27", 
     "maxtempF": "80", 
     "mintempC": "15", 
     "mintempF": "58", 
     "hourly": [{ 
      "time": "0", 
      "tempC": "15", 
... 

kehrt Obwohl ich nur bin Erhalten der Antwort von Undefined. Warum? Vielen Dank im Voraus.

+0

Asynchroner Funktionsaufruf – Satpal

Antwort

1

Sie müssen die console.log innerhalb des Callbacks setzen, andernfalls wird es ausgeführt, bevor der Callback mit den Daten vom Server zurückkehrt.

const request = require('request') 
const apiKey = 'XXXXXXXXXXXXXX' 

var dat; 
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx' 
let qs = { 
q: '-34.48,150.92', 
format: 'json', 
apiKey 
} 
request({ url, qs }, (err, response, body) => { 
if (err) 
return console.error(err) 
if (response.statusCode != 200) 
return console.error('status code is', response.statusCode) 
body = JSON.parse(body) 
dat = body.data.hourly[0].tempC 
console.log(dat); 
}) 
+1

Wir brauchen noch keine Antwort auf diese Frage. :-) –