【问题标题】:How to get data out of request handler如何从请求处理程序中获取数据
【发布时间】: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


【解决方案1】:

你可以这样写代码

   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);
      } 
    }

【讨论】:

  • 试一试,但它似乎不起作用。我已经编辑了我的代码,使其更加清晰。
猜你喜欢
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2012-01-08
  • 1970-01-01
相关资源
最近更新 更多