admin管理员组文章数量:1310228
How can I add csrf token with my ajax requests (GET or POST) of my Laravel application automatically without adding it manually to each and every request.
My ajax Request
$.ajax({
type:'post',
url: "/email/unique",
data: { "_token": "{{ csrf_token() }}", "email": email }
success: function(data) {
console.log(data);
}
});
How can I add csrf token with my ajax requests (GET or POST) of my Laravel application automatically without adding it manually to each and every request.
My ajax Request
$.ajax({
type:'post',
url: "/email/unique",
data: { "_token": "{{ csrf_token() }}", "email": email }
success: function(data) {
console.log(data);
}
});
Share
Improve this question
asked Dec 8, 2018 at 17:12
PrateekPrateek
1,2471 gold badge17 silver badges33 bronze badges
1 Answer
Reset to default 7In Laravel the value of the csrf-token meta tag registers by default with the Axios HTTP library. But If you are not using this library, you will need to manually configure this behavior for your application.
To do this, store the token in a HTML meta tag
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct the jQuery library to automatically add the token to all the request headers.
For that add the code to the resources/js/bootstrap.js
file for Laravel 5.7
and resources/assets/js/bootstrap.js
for Laravel 5.6
and below versions.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Ajax without csrf token as it will get added automatically
$.ajax({
type:'post',
url: "/email/unique",
data: { "email": email }
success: function(data) {
console.log(data);
}
});
本文标签: javascriptHow to automatically add XCSRFTOKEN with jQuery ajax request in LaravelStack Overflow
版权声明:本文标题:javascript - How to automatically add X-CSRF-TOKEN with jQuery ajax request in Laravel - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741835760a2400204.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论