正在node.js中等待HTTP请求

正在node.js中等待HTTP请求,node.js,express,request,openweathermap,Node.js,Express,Request,Openweathermap,我知道其他人问过这个问题,我需要使用回调,但我不太确定如何将它们与代码集成 我正在使用node.js和express来创建一个网站,在页面加载时,我希望该网站能够抓取天气,等待响应,然后加载页面 我的“WeatherApp”代码如下: const config=require('./config'); const request=require('request'); 函数首字母大写(字符串){ 返回string.charAt(0.toUpperCase()+string.slice(1);

我知道其他人问过这个问题,我需要使用回调,但我不太确定如何将它们与代码集成

我正在使用node.js和express来创建一个网站,在页面加载时,我希望该网站能够抓取天气,等待响应,然后加载页面

我的“WeatherApp”代码如下:

const config=require('./config');
const request=require('request');
函数首字母大写(字符串){
返回string.charAt(0.toUpperCase()+string.slice(1);
}
module.exports={
getWeather:function(){
请求(config.weatherdomain,函数(err,response,body){
如果(错误){
console.log('error:',error);
}否则{
让weather=JSON.parse(body);
让返回字符串={
温度:数学循环(天气、主温度),
类型:weather.weather[0]。说明
}
return JSON.stringify(returnString);
}
});
}

}
您混合了同步和异步方法,这就是为什么会出现这种问题

我建议查看这些帖子,了解其中的区别

关于你的问题。解决办法很简单。添加回调

getWeather: function(callback) {
    request(config.weatherdomain, function(err, response, body) {
        if (err) {
            callback(err, null)
        } else {
            let weather = JSON.parse(body);
            let returnString = {
                temperature: Math.round(weather.main.temp),
                type: weather.weather[0].description
            }
            callback(null, JSON.stringify(returnString));
       }
    });
}
现在在路上

router.get('/', function(req, res, next) {
weatherApp.getWeather(function(err, result) {
     if (err) {//dosomething}
     res.render('index', {
        title: 'Home',
        data: weather
      });
    });
});

希望这有帮助。

Np。很乐意帮忙。