Angular csrf token

By: Ryan Wong at

One way to implement CSRF token in angular is to put csrf token in a meta tag and pull it from angular as a constant.

JS:

1
2
3
4
5
6
7
8
9
10
11
12
var app = angular.module('home', [])
.constant('CSRF_TOKEN', csrftoken)
var csrftoken = (function() {
// not need Jquery for doing that
var metas = window.document.getElementsByTagName('meta');
// finding one has csrf token
for(var i=0 ; i < metas.length ; i++) {
if ( metas[i].name === "csrf-token") {
return metas[i].content;
}
}
})();

HTML:

1
<meta content="{{csrf_token()}}" name="csrf-token"/>