ajaxリクエストをライブラリにまとめようとしています。私はこれを行っているので、リクエストを行うたびにヘッダーを設定する必要はありません。ライブラリは非同期で読み込まれ、APIキーを設定するためのinitメソッドがあります。コードは機能しているようですが、API呼び出しを開始するたびに2つのリクエストが発生します。ライブラリは非常に基本的で、完成にはほど遠いです。
リクエストが行われているAPIは、ノードおよびエクスプレスベースのAPIからのものです。Restクライアントで同じリクエストが行われると、それらはすべて正しいデータとhttpステータスコードを返します。
ライブラリをロードするコードは次のとおりです。
(function(d) {
var api_key='MY-API-KEY';
var js,id='tracking-api',ref=d.getElementsByTagName('script')[0];
if(d.getElementById(id)){return;}
js=d.createElement('script');js.id=id;js.async=true;
js.src="/test/track.api.min.js";
js.onload=function(){stats.init({api_key:api_key})}
ref.parentNode.insertBefore(js, ref);
})(document);
縮小されていないライブラリ:
(function(window){
'use strict';
/**
* This library requires jquery to run
*/
var stats= {
url : 'http://localhost/stats_api/',
api_key: undefined,
// The init method will take an api key and set it for our headers
// used with all api requests
init: function(opts) {
if(opts.api_key === undefined) {
stats.logMsg('Sorry you need to supply an api key');
return false;
}
stats.api_key = opts.api_key;
},
// Main api call method nice and simple use - we just give it the
// method we require and we will be given a json response
api: function(method, callback) {
jQuery.ajax({
url: stats.url + method,
dataType: 'JSON',
type: 'GET',
beforeSend: function(xhr) {
xhr.setRequestHeader('api_key', stats.api_key);
},
success: function(response) {
callback(response);
},
error: function(jqXHR, textStatus, errorThrown) {
btStats.logMsg(jqXHR);
btStats.logMsg('Error:' + textStatus);
}
});
},
// Wrap up the console log function so we can still use it but
// not break IE8
logMsg: function(message) {
if(window.console && console.log) {
console.log(message);
}
}
};
// Attatch our plugin to the window
if(!window.stats){window.stats=stats};
})(window);
次にAPIリクエストを行うために使用するコードは次のようになります。
stats.api('/visits', function(response){
console.log(response);
});
応答は常に正しく返されますが、要求の大部分は404です。それらが404になると、2回目のクエリも実行されるようです。
質問は、なぜリクエストが2回行われるのかということだと思います。リクエストが成功したときにjQueryが404を返すのはなぜですか。