【发布时间】:2017-07-29 15:10:06
【问题描述】:
我正在使用 express、node 和车把。我有这段代码用于处理 POST。如果用户单击“添加项目”按钮,它会输入一个城市,使用 Open Weather Map 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>"
}
}
但是,温度变量返回“未定义”。我认为这与异步性有关,但我不确定我应该做些什么来纠正它。
【问题讨论】:
-
你没有。这不是范围问题,而是时间问题。您不知道请求何时返回,请求处理程序被触发,因此
temprature可用。您必须在请求处理程序中放置/调用依赖于temperature的所有逻辑。
标签: javascript node.js express asynchronous