How to add header for all RESTAdapter ember requests

Seif Sallam picture Seif Sallam · Jun 3, 2013 · Viewed 10.1k times · Source

The API needs to specify api version application/vnd.api+json;version=1, also it needs secure x-app-id and x-app-secret. Is there a way to specify that in RESTAdapter in Ember?

After Trying request header

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

UPDATE #2

The solution mentioned above is no longer needed, as Ember now supports this behavior by default. You only need to supply headers and it will automatically be added.

Check out the docs here http://emberjs.com/guides/models/connecting-to-an-http-server/#toc_custom-http-headers

Answer

Cory Loken picture Cory Loken · Jun 4, 2013

At the core the RESTAdapter uses jQuery for Ajax, you can set headers with $.ajaxSetup or a more Ember way with Ember.$.ajaxSetup which would ideally protect you against lower level changes to the API.

jQuery Doc: http://api.jquery.com/jQuery.ajaxSetup/

SO with examples:

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