2017-03-08 47 views
-1

我正在使用express,node和handlebars。我有這段代碼來處理POST。如果用戶點擊「添加項目」按鈕,則它將輸入城市,使用打開天氣地圖API查找該城市的天氣,並根據天氣更改該城市項目背景的顏色。如何從請求處理程序中獲取數據

app.post('/',function(req,res){ 
    var context = {}; 
    var temperature; 

    if(req.body['Add Item']){ 
    req.session.toDo.push({"name":req.body.name, "id":req.session.curId, "location":req.body.city}); 
    req.session.curId++; 

    request('http://api.openweathermap.org/data/2.5/weather?q=' + req.body.city + '&units=imperial&APPID=' + credentials.owmKey, handleGet); 

    function handleGet(err, response, body){ 
     if(!err && response.statusCode < 400){ 
     context.owm = body; 
     var newText = JSON.parse(context.owm); 
     temperature = newText.main.temp; 
     } 
    } 
    } 
... 

    if(temperature > 70) { 
    context.script = "<script>document.getElementById('owm').style.backgroundColor='LightGreen';</script>" 
    } 

    else if (temperature < 70){ 
    context.script = "<script>document.getElementById('owm').style.backgroundColor='LightPink';</script>" 
    } 
} 

但是,溫度變量返回'未定義'。我認爲這必須做一些與異步性有關的事情,但我不知道我應該怎麼做來糾正它。

+1

**你不**。這不是一個範圍問題,這是一個計時問題。您不知道請求何時返回,請求處理程序被觸發,因此「temprature」可用。您必須在請求處理程序中放入/調用所有依賴於「溫度」的邏輯。 – Thomas

+1

接近dup:[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous -呼叫)。 – jfriend00

回答

0

你可以寫這樣的代碼

function handleGet(err, response, body){ 
     if(!err && response.statusCode < 400){ 
     context.owm = body; 
     var newText = JSON.parse(context.owm); 
     temperature = newText.main.temp; 
     if(temperature > 70) { 
      context.script = "<script>document.getElementById('owm').style.backgroundColor='LightGreen';</script>" 
     } else if (temperature < 70){ 
      context.script = "<script>document.getElementById('owm').style.backgroundColor='LightPink';</script>" 
     } 
     console.log('temp inside is '+ temperature); 
     } 
    } 
+0

給它一個鏡頭,但它似乎並沒有工作。我編輯了我的代碼,使其更清晰一些。 –

相關問題