2013-06-03 29 views
12

API需要指定API版本application/vnd.api+json;version=1,它還需要安全的x-app-id和x-app-secret。有沒有一種方法可以在Ember中的RESTAdapter中指定?如何爲所有RESTAdapter實體請求添加頭文件

試圖請求頭

App.Adapter = DS.RESTAdapter.extend({ 
    namespace: 'api', 
    beforeSend: function(xhr) { 
    xhr.setRequestHeader('x-my-custom-header', 'some value'); 
    } 
}) 

SOLUTION
App.Adapter = DS.RESTAdapter.extend({ 
    bulkCommit: true, 
    namespace: 'api', 
    headers: { 
    'Accept': 'application/vnd.app+json;version=1', 
    'x-appid': '2375498237', 
    'x-secret': '238945298235236236236236375923' 
    }, 
    ajax: function(url, type, hash) { 
    if (this.headers !== undefined) { 
     var headers = this.headers; 
     hash.beforeSend = function (xhr) { 
     Ember.keys(headers).forEach(function(key) { 
      xhr.setRequestHeader(key, headers[key]); 
     }); 
     }; 
    } 
    return this._super(url, type, hash); 
    } 
}); 

App.Store = DS.Store.extend({ adapter: App.Adapter.create() }); 
App.Store = App.Store.create(); 

更新#2

如上所述不再需要,因爲現在灰燼默認支持此行爲的溶液。您只需要提供headers,它會自動添加。

退房這裏http://emberjs.com/guides/models/connecting-to-an-http-server/#toc_custom-http-headers

+0

不是爲我工作;當我查看請求時,其中沒有標題。任何想法 ?版本問題mabye? – fabien

+0

你叫 '''App.Store = DS.Store.extend({adapter.Adapter.create() });'''Then'''App.store = App.Store.create );'''添加上面的代碼後? –

+0

而且工作:)謝謝 – fabien

回答

5

的文檔在RESTAdapter用jQuery進行Ajax的核心,你可以用$ .ajaxSetup或與Ember。$更灰燼的方式設置頭。ajaxSetup這將最好保護您免受下對API的級別更改。

jQuery的文檔: http://api.jquery.com/jQuery.ajaxSetup/

SO舉例:

How can I add a custom HTTP header to ajax request with js or jQuery?

+0

好吧,關於如何安全地放置x-app-secret的任何想法? –

+0

另請參閱https://github.com/emberjs/data/issues/722 –

+0

任何可以複製的內容。我無法在我的項目中找到任何人工作。或者我不知道如何整合它們。 –

相關問題