13

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

Seif Sallam
  • 821
  • 2
  • 10
  • 30
  • Not working for me ; when I look at the request, there's no headers in it. Any idea ? A version problem mabye ? – fabien Jun 17 '13 at 19:01
  • Do you call ```App.Store = DS.Store.extend({ adapter: App.Adapter.create() });``` Then ```App.store = App.Store.create();``` After you add the above code? – Seif Sallam Jun 17 '13 at 20:00
  • Any solutions WITHOUT Ember-Data ?! – V-Light Jun 19 '14 at 15:13
  • @V-Light It's easy to do using jQuery – Seif Sallam Jun 19 '14 at 16:38
  • @SeifSallam yeah, I was able to $.ajaxSetup globaly without Ember-Data with [Ember Initializers](http://mcdowall.info/posts/ember-application-initializers/) – V-Light Jun 23 '14 at 10:14
  • For people who copy paste: the correct mime-type is [application/vnd.api+json](http://jsonapi.org/#mime-types). – adriaan Sep 02 '14 at 10:30

1 Answers1

5

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?

Community
  • 1
  • 1
Cory Loken
  • 1,395
  • 8
  • 8