I am working on a Laravel 5 app that has CSRF protection enabled by default for all POST requests. I like this added security so I am trying to work with it.
While m
no need to set any meta tag neither the csrf_token() nor the csrf_field() !
You could use this jQuery snippet :
$.ajaxPrefilter(function( settings, original, xhr ) {
if (['post','put','delete'].includes(settings.type.toLowerCase())
&& !settings.crossDomain) {
xhr.setRequestHeader("X-XSRF-TOKEN", getCookie('XSRF-TOKEN'));
}
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
just few other answers tried to set the csrf header but according the Laravel documents (here) , the header key should be "X-XSRF-TOKEN" and Laravel itself provides the needed value on every request for us in a cookie named "XSRF-TOKEN"
so just corrected the keys and edited few lines,thanks