Created
September 11, 2012 13:45
-
-
Save prognostikos/3698589 to your computer and use it in GitHub Desktop.
AngularJS & Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} | |
}]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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
Not one, but two useful things I found here! Thanks.