2013-03-15 106 views
0

我試圖將ajax請求包裝到庫中。我這樣做,所以我不需要每次我提出請求時設置標題。該庫是異步加載的,並有一個init方法來設置API密鑰。代碼似乎可行,但每次我發起api調用時,都會收到2個請求。圖書館非常基礎,遠未完成。jQuery ajax 404,但仍然得到結果

請求正在進行的api來自基於api的節點&。當其他客戶端發出相同的請求時,他們都會返回正確的數據& 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); 

將未精縮庫:使用到,然後做一個API請求

(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); 

代碼IM是像這樣:

stats.api('/visits', function(response){ 
    console.log(response); 
}); 

該響應總是正確返回,但大部分請求404。當它們404也似乎是再次運行查詢。

所以我想問題是,爲什麼請求被做兩次?爲什麼jQuery在請求成功時返回404。

+0

哪個瀏覽器,你是按CLT + F5? – 2013-03-15 13:35:52

+0

在這裏看到http://stackoverflow.com/questions/5544422/jquery-ajax-executed-twice – PSR 2013-03-15 13:36:18

+0

即時通訊在Mac OS X上使用鉻版本25和請求是相同的,無論我如何加載頁面 – 2013-03-15 13:37:26

回答

1

好吧,事實證明這是一個非常簡單的問題,因爲我的代碼正在運行跨域jQuery發送一個OPTIONS方法的預檢請求(沒有注意到這一點)404是來自我的節點api由於該方法不支持用於試驗的我增加了一些中間件到API

app.use(function(req, res, next){ 

    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With"); 
    res.header("Access-Control-Allow-Headers", "api_key"); 

    if(req.method == 'OPTIONS') { 
     res.send(200); 
    } 
    else { 
     next(); 
    } 

}); 

並不理想,因爲這將允許跨域腳本的所有路由,所以我將不得不稍後鎖定下來。

相關問題