Angular2 Http Laravel CSRF令牌 [英] Angular2 Http Laravel CSRF Token
问题描述
混淆了一些Angular2教程并试图获得在Laravel 5.2中工作的帖子请求我添加了这个元标记:
Muddling through some Angular2 tutorials and trying to get a post request to work in Laravel 5.2 I have added this meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
但是我不知道如何在标题部分传递它,或者老实说,如果它在那里它应该去。
but I'm not sure how to pass that in the headers section or honestly if that is where it should go.
let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '???????' });
更新:所以我添加了一个函数来从元标记中提取csrf-token但仍然没有找到了一种方法将它传递给Laravel帖子请求。
Update: So I added a function to pull the csrf-token from the meta tag but still have not found a way to get it passed to the Laravel post request.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
谢谢
推荐答案
这就是我所做的。不确定它是否是最佳方式,但它有效。
This is what I did. Not sure if it is the best way but it worked.
在Laravel主模板中,我添加了这个元标记。
In the main Laravel template I added this meta tag.
<meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">
在Angular2 whatever.service.ts中我添加了一个获取令牌函数。
In the Angular2 whatever.service.ts I added a get token function.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
在同一服务中,我将此添加到post方法。
In the same service I added this to the post method.
let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': this.getToken()});
Laravel现在接受没有500令牌不匹配错误的帖子
Laravel now accepts the post without the 500 Token Mismatch Error
如果有更好的解决方案,请加入!
Please chime in if there is a better solution!!
这篇关于Angular2 Http Laravel CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!