Skip to content

Instantly share code, notes, and snippets.

@prognostikos
Created September 11, 2012 13:45
Show Gist options
  • Save prognostikos/3698589 to your computer and use it in GitHub Desktop.
Save prognostikos/3698589 to your computer and use it in GitHub Desktop.
AngularJS & Rails
/**
* Angular needs to send the Rails CSRF token with each post request.
*
* Here we get the token from the meta tags (make sure <%= csrf_meta_tags %>
* is present in your layout.)
*/
angular.module('myapp',[]).
// configure our http requests to include the Rails CSRF token
config(["$httpProvider", function(p) {
var m = document.getElementsByTagName('meta');
for (var i in m) {
if (m[i].name == 'csrf-token') {
p.defaults.headers.common['X-CSRF-Token'] = m[i].content;
break;
}
}
}]);
MyApp::Application.configure do |config|
# Don't mangle Angular's special variable names!
config.assets.js_compressor = Sprockets::LazyCompressor.new { Uglifier.new(:mangle => false) }
end
@victorbstan
Copy link

Not one, but two useful things I found here! Thanks.

@Hengjie
Copy link

Hengjie commented May 30, 2013

You could just do this to get the token so that you don't need to loop through the whole thing:

$('meta[name="csrf-token"]').attr('content')

Also you probably want to set the 'Accept' header to application/json

@bradgreens
Copy link

Can also sniff the DOM the angular way if you're not using jQuery.
angular.element( document.querySelectorAll('meta[name=csrf-token]') ).attr('content')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment