私は他の人がこの質問をしていることを知っており、コールバックを使用する必要があることを知っていますが、node.jsでHTTPリクエストを待っています
エクスプレスでnode.jsを使用してウェブサイトを作成しています。ページを読み込む際には、サイトを訪れて天気を捉え、応答を待ってからページを読み込んでください。
次のように私の '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 });
});
ありがとうございました! :) –
Np。喜んで助けてください。 –