LoginSignup
0
0

More than 3 years have passed since last update.

ブラウザのXMLHttpRequest(xhr)で今日の東京の天気を取得する

Last updated at Posted at 2020-04-28

Open Weather Mapを試してみます。livedoorの天気APIはhttpsが使えない模様でそろそろブラウザからアクセスするのには厳しそうでした。

東京の今日の天気を取得するサンプルリクエスト

こちらをブラウザから叩くと取得できます。 appidはユーザー登録をして取得しましょう。

https://api.openweathermap.org/data/2.5/weather?id=1850147&units=metric&appid=**************

Open Weather Mapは初めてでしたが、OpenWeatherMapで気象情報をゲットしようが参考になりました。返却値のオブジェクトはここをみるとだいたいわかります。

ブラウザのxhrでGETリクエスト

function getWeather(){
    const url = 'https://api.openweathermap.org/data/2.5/weather?id=1850147&units=metric&appid=xxxxxxxxxxxxxxxxx';

    const xhr = new XMLHttpRequest();
    xhr.open("GET", url, false);
    xhr.onload = function () {
        const res = JSON.parse(xhr.response);
        const weather = res.weather[0].main;
        console.log(weather);
    };
    xhr.send(null);
}

getWeather();

Promiseで使う

大体の場合、"天気が晴だったら何かする"とか"温度が何度以上だったら何かする"という使い方になると思うのでプロミスで使う用のもメモ

function getWeather(){
    const url = 'https://api.openweathermap.org/data/2.5/weather?id=1850147&units=metric&appid=xxxxxxxxxxxxxxxxx';

    return new Promise(function(resolve, reject){
        const xhr = new XMLHttpRequest();
        xhr.open("GET", url, false);
        xhr.onload = function () {
            const res = JSON.parse(xhr.response);
            const weather = res.weather[0].main;
            resolve(weather);
        };
        xhr.send(null);
    })
}

getWeather().then(function(res){
    console.log(res);
    if(res === 'Clouds'){//曇りならば~

    }
})
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0