質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
HttpWebRequest

HttpWebRequestとは.NETにおけるクラスであり、WebRequestクラスをHTTPに導入するものです。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Q&A

解決済

2回答

481閲覧

Node.jsでhttpのリクエストをモジュール化したい

minato86

総合スコア15

HttpWebRequest

HttpWebRequestとは.NETにおけるクラスであり、WebRequestクラスをHTTPに導入するものです。

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

0グッド

0クリップ

投稿2019/07/17 06:38

実現したいこと

OpenWeatherMapのAPIを使い天気を取得する処理をopenweather.jsファイルにしてmain.jsからrequireして使いたい。

バージョン等

OS: Windows10 Pro 64bit
エディタ: Atom 1.38.2 x64
Node.js: v10.16.0
yarn: 1.16.0

現状

ファイル構造

JS_WARBot ├─ lib │ └─ openweather.js ├─ node_modules │ └─ ... ├─ package.json ├─ main.js └─ yarn.lock

コード

main.js

node.js

1const openweather = require('./lib/openweather.js') 2 3cityid = "6940394" 4 5async function getweather(cityid){ 6 let result = await openweather.get(cityid); 7 console.log(result); 8} 9getweather(cityid);

./lib/openweather.js

node.js

1const http = require('http'); 2var APIKEY = "***************"; 3 4function get(cityid) { 5 var URL = 'http://api.openweathermap.org/data/2.5/forecast?id='+ cityid +'&units=metric&lang=ja&APPID='+ APIKEY; 6 console.log(URL); 7 function getPromise(URL){ 8 return new Promise((resolve, reject)=>{ 9 http.get(URL, function(res) { 10 let body = ''; 11 res.setEncoding('utf8'); 12 13 res.on('data', function(chunk) { 14 body += chunk; 15 }); 16 17 res.on('end', function(chunk) { 18 res = JSON.parse(body); 19 20 var day_num = 0; 21 var day = "今日"; 22 23 if (res.list[day_num].rain !== undefined) { 24 var result = `:umbrella2: ${day}の天気予報 :sun_with_face:\n\n天気: ${res.list[day_num].weather[0].description}\n` 25 +`雨量: 3時間あたり${res.list[day_num].rain["3h"]}mm\n最低気温: ${res.list[day_num].main.temp_min}℃\n` 26 +`最高気温: ${res.list[day_num].main.temp_max}℃\n\n` 27 +`:small_orange_diamond:この天気は${day}のこの時間の天気を表示しています。\n他の時間の天気はこちら :point_right: https://openweathermap.org/city/${res.city.id}\n\n` 28 +`:open_file_folder: 天気データ提供: openweathermap.org` 29 resolve(result); 30 } else { 31 var result = `:umbrella2: ${day}の天気予報 :sun_with_face:\n\n天気: ${res.list[day_num].weather[0].description}\n` 32 +`最低気温: ${res.list[day_num].main.temp_min}℃\n最高気温: ${res.list[day_num].main.temp_max}℃\n\n` 33 +`:small_orange_diamond:この天気は${day}のこの時間の天気を表示しています。\n他の時間の天気はこちら :point_right: https://openweathermap.org/city/${res.city.id}\n\n` 34 +`:open_file_folder: 天気データ提供: openweathermap.org`; 35 resolve(result); 36 } 37 }) 38 }) 39 }) 40 } 41 getPromise(URL).then(result => { 42 console.log(result); 43 return result; 44 }) 45 46} 47 48module.exports.get = get;

起こっている問題

openweather.jsconsole.logでは正常なデータが表示されるのですが、main.jsconsole.logではundefinedとなってしまいます。

インターネットでは、この手の問題はPromise等をと使えば解決できるとのことですが、一向に解決できないので質問させていただきます。

よろしくお願い致します。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

最終的に自己解決しましたのでその方法を記しておきます。

main.js

node.js

1const openweather = require('./lib/openweather.js') 2 3cityid = "6940394" 4 5async function getweather(cityid){ 6 let result = await openweather.get(cityid); 7 return result; 8} 9getweather(cityid).then((res) => { 10 console.log(res); 11});

./lib/openweather.js

node.js

1const http = require('http'); 2var APIKEY = "************************"; 3 4function get(cityid) { 5 var result = new Promise((resolve, reject)=>{ 6 var URL = 'http://api.openweathermap.org/data/2.5/forecast?id='+ cityid +'&units=metric&lang=ja&APPID='+ APIKEY; 7 http.get(URL, function(res) { 8 let body = ''; 9 res.setEncoding('utf8'); 10 11 res.on('data', function(chunk) { 12 body += chunk; 13 }); 14 15 res.on('end', function(chunk) { 16 res = JSON.parse(body); 17 18 var day_num = 0; 19 var day = "今日"; 20 21 if (res.list[day_num].rain !== undefined) { 22 var result = `:umbrella2: ${day}の天気予報 :sun_with_face:\n\n天気: ${res.list[day_num].weather[0].description}\n` 23 +`雨量: 3時間あたり${res.list[day_num].rain["3h"]}mm\n最低気温: ${res.list[day_num].main.temp_min}℃\n` 24 +`最高気温: ${res.list[day_num].main.temp_max}℃\n\n` 25 +`:small_orange_diamond:この天気は${day}のこの時間の天気を表示しています。\n他の時間の天気はこちら :point_right: https://openweathermap.org/city/${res.city.id}\n\n` 26 +`:open_file_folder: 天気データ提供: openweathermap.org` 27 resolve(result); 28 } else { 29 var result = `:umbrella2: ${day}の天気予報 :sun_with_face:\n\n天気: ${res.list[day_num].weather[0].description}\n` 30 +`最低気温: ${res.list[day_num].main.temp_min}℃\n最高気温: ${res.list[day_num].main.temp_max}℃\n\n` 31 +`:small_orange_diamond:この天気は${day}のこの時間の天気を表示しています。\n他の時間の天気はこちら :point_right: https://openweathermap.org/city/${res.city.id}\n\n` 32 +`:open_file_folder: 天気データ提供: openweathermap.org`; 33 resolve(result); 34 } 35 }) 36 }) 37 }) 38 return result; 39} 40 41module.exports.get = get;

自己解決はしたものの、回答を頂けなければこの答えにたどり着くことはできなかったと思います。
ありがとうございました。

投稿2019/07/17 11:42

minato86

総合スコア15

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

openweather.getの戻り値がPromiseです。つまり天気の結果ではありません

今の書き方だと、
let result = await openweather.get(cityid);の下の行で
result.then((weather) => { console.log(weather); })
と書けばいいはずです

投稿2019/07/17 07:14

youk-h

総合スコア25

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

minato86

2019/07/17 07:30

教えていただいた方法を試したのですが、 UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'then' of undefined と出て結果が得られませんでした。
youk-h

2019/07/17 08:07 編集

すみません、見落としていました。 openweather.getは今なにもreturnしてないので戻り値がvoidになってますね openweather.get内の getPromise(URL).then(result => { console.log(result); return result; }) を return getPromise(URL).then(result => { console.log(result); return result; }) もしくは return getPromise(URL); に書き換える そして、さっきのやつを試してみてください
minato86

2019/07/17 08:38

UnhandledPromiseRejectionWarning: TypeError: result.then is not a function と出ました。 return getPromise(URL);に書き換えた場合も、先頭にreturnを置いた場合も、同様の結果でした。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問