2017-03-08 55 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

给它一个镜头,但它似乎并没有工作。我编辑了我的代码,使其更清晰一些。 –

相关问题