在node.js中等待HTTP请求

问题描述:

我知道其他人问过这个问题,我需要使用回调函数,但我不太确定如何将它们与我的代码集成。在node.js中等待HTTP请求

我使用node.js和express来制作一个网站,并且在页面加载时我希望网站去抓住天气,等待响应,然后用它加载页面。

我 'WeatherApp' 代码如下:

const config = require('./config'); 
 
const request = require('request'); 
 

 
function capitalizeFirstLetter(string) { 
 
\t return string.charAt(0).toUpperCase() + string.slice(1); 
 
} 
 
module.exports = { 
 
\t getWeather: function() { 
 
\t \t request(config.weatherdomain, function(err, response, body) { 
 
\t \t \t if (err) { 
 
\t \t \t \t console.log('error:', error); 
 
\t \t \t } else { 
 
\t \t \t \t let weather = JSON.parse(body); 
 
\t \t \t \t let returnString = { 
 
\t \t \t \t \t temperature: Math.round(weather.main.temp), 
 
\t \t \t \t \t type: weather.weather[0].description 
 
\t \t \t \t } 
 
\t \t \t \t return JSON.stringify(returnString); 
 
     } 
 
\t \t }); 
 
\t } 
 
}

而且我的页面当前路由:

router.get('/', function(req, res, next) { 
 
\t var weather; 
 
\t weather = weatherApp.getWeather(); 
 
\t res.render('index', { 
 
\t \t title: 'Home', 
 
\t \t data: weather 
 
\t }); 
 
});

幽秘x同步和异步方法,这就是为什么你会遇到这个问题。

我建议查看这篇文章了解差异。

What is the difference between synchronous and asynchronous programming (in node.js)

Synchronous vs Asynchronous code with Node.js

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

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

希望这有助于。

+0

非常感谢! :) –

+0

Np。乐意效劳。 –