2017-08-12 8 views
-2

私は他の人がこの質問をしていることを知っており、コールバックを使用する必要があることを知っていますが、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 }); 
 
});

答えて

0

あなたマイル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。喜んで助けてください。 –

関連する問題