Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only update the headers for local requests #12

Open
ychaker opened this issue Nov 10, 2015 · 0 comments
Open

Only update the headers for local requests #12

ychaker opened this issue Nov 10, 2015 · 0 comments

Comments

@ychaker
Copy link

ychaker commented Nov 10, 2015

Hey,
this is not an issue as much as it is a thank you!

I was able to use the code from your gem to do the following in my app:

angular.module('ng-rails-csrf', [] ).config(['$httpProvider', function($httpProvider) {
  var getToken = function() {
    var el = document.querySelector('meta[name="csrf-token"]');

    if (el) {
      el = el.getAttribute('content');

    }
    return el;
  };

  $httpProvider.interceptors.push(function() {
    return {
     'request': function(config) {
        if ( config.url.indexOf('/api') == 0 ) {
          var headers = config.headers;
          var token   = getToken();

          if (token) {
            headers['X-CSRF-TOKEN']     = token;
            headers['X-Requested-With'] = 'XMLHttpRequest';
          }
        }

        return config;
      }
    };
  });
}]);

The idea is that I didn't want to set the csrf token globally for all the requests because there are some requests that are external to other services (and need to be in the Angular app, not the Rails backend).

So instead of setting the default headers for all request, I created an interceptor that checks if the request is going to the local API, and only sets the csrf token for those specific requests.

Anyway, I wanted to say thank you for sharing your code which helped figure out what I needed to do.
And I'm sharing this here just in case anyone is trying to solve the same problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant