Adding headers after initializing the RESTAdapter

I am trying to add a header Authorizationto my adapter request after initializing and using the adapter. I can add headers statically when I create my own ApplicationAdapter, but I cannot force it to use headers in subsequent REST calls. I try this:

var auth= "Basic " + hash;
App.ApplicationAdapter.reopen({
    headers: {
        Authorization: auth
    }
});

I debugged RESTAdapterin the method ajax, and the test for adapter.headersalways undefined.

+4
source share
3 answers

The accepted answer does not take into account the fact that the recommended approach does not work in ember data. I recommend since:

https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js#L88

https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js#L162 .

, , OP undefined, : https://github.com/emberjs/data/blob/master/packages/ember-data/lib/adapters/rest_adapter.js#L619

, :

App.ApplicationAdapter.reopen({
  headers: {token: 'reopen_token (NO WORK)' }
});

, : https://github.com/emberjs/data/issues/1820

, ​​ , . , , jQuery ajax setup, Ember. $. AjaxPrefilter ajax .

EDIT: , Ember, , ​​ , . , , ( ), , . , ( pull, : https://github.com/emberjs/data/pull/1818/files#diff-1d7f5a5b77898df15de501c3c38d4829R108)

2: , , - :

//app.js
App.ApplicationAdapter = DS.ActiveModelAdapter.extend({
  namespace: 'api/v1',
  headers: function() {
    return {
      token: this.get('App.authToken') || localStorage.getItem('token')
    };
  }.property("App.authToken")
});

//login-controller.js (only action shown..assume `data` has user/pass)
  actions: {
    login: function() {
        $.post('/token/', data).done(function(user) {
          App.set('authToken', user.token);
          //Above will trigger adapters header computed property to update

          // Transition to previous attempted route
          var attemptedTransition = self.get('attemptedTransition');
          if(attemptedTransition) {
            attemptedTransition.retry();
          }
          else {
            self.transitionToRoute('yourapproute');
          }
        })
        .fail(function(response) { 
          //fail handling omitted
        });
+9

You can use $.ajaxPrefilterto add custom headers (or parameters).

See: http://api.jquery.com/jQuery.ajaxPrefilter/

Ember.$.ajaxPrefilter(function( options, oriOptions, jqXHR ) {
  var auth= "Basic " + hash;
  jqXHR.setRequestHeader("Authorization", auth);
});
0
source

Source: https://habr.com/ru/post/1524781/


All Articles