openweathermap APIを使用してデータを取得しようとしています。私はそれを動作させることができますが、私はそれを非同期的に行うことはできません。これは、次のエラーが発生します。openweathermap APIを使用して天気を非同期的に取得できません。
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
フォーム:
<label>Zipcode: </label>
<form>
<input type="text" id="locationField" name="locationField">
<input type="submit" id="weatherSubmit" value="Get Weather">
</form>
<div>
<br>
<label>Location:</label>
<div id="location"></div>
<br>
<label>Temperature:</label>
<div id="temperature"></div>
<br>
<label>Humidity</label>
<div id="humidity"></div>
</div>
スクリプト:
document.getElementById('weatherSubmit').addEventListener('click', function(event) {
var zipcode = document.getElementById('locationField').value;
var req = new XMLHttpRequest();
var payload = {location: null, temperature:null, humidity:null};
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + zipcode + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
if(req.status >= 200 && req.status < 400){
var response = JSON.parse(req.responseText);
document.getElementById('location').textContent = response.name;
document.getElementById('temperature').textContent = response.main.temp;
document.getElementById('humidity').textContent = response.main.humidity;
} else {
console.log("Error in network request: " + request.statusText);
}});
req.send(JSON.stringify(payload));
event.preventDefault();
});
私は、私はAJAXを使用していない場合は、この作業を取得することができますが、それは私がそれをしたいのではありません。次のコードは、foo()
が送信ボタンからonclick呼び出され、郵便番号の値を渡す場合に機能します。
function foo(value) {
var req = new XMLHttpRequest();
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", false);
req.send(null);
var response = JSON.parse(req.responseText);
document.getElementById('location').textContent = response.name;
var f = ((response.main.temp - 273.15) * 9/5) + 32;
document.getElementById('temperature').textContent = f + "f";
document.getElementById('humidity').textContent = response.main.humidity + "%";
}
コンテンツタイプを設定してリクエストボディを送信するので、最初のリクエストは 'POST 'で行われませんか? – Musa
' GET'でも 'POST'でも動作しません – 123
おそらくあなたのアプリケーションコードをあなたのサンプルコードから削除する必要があります... – robertklep