问题
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': '???????' });
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;
}
Thanks
回答1:
This is what I did. Not sure if it is the best way but it worked.
In the main Laravel template I added this meta tag.
<meta property="csrf-token" name="csrf-token" content="{{ csrf_token() }}">
In the Angular2 whatever.service.ts I added a get token function.
getToken() {
let token = document.querySelector('meta[property="csrf-token"]')['content'];
return token;
}
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 now accepts the post without the 500 Token Mismatch Error
Please chime in if there is a better solution!!
回答2:
This should be the same "problem" as with <title>{{ title() }}</title>: There's no component. This means: Angular won't/can't do any interpolation here. For the title tag the angular team provides an injectable Title service. For meta tags you've got to roll your own solution.
Have a look here: https://wijmo.com/blog/how-to-improve-seo-in-angularjs-applications/
They use document.querySelector to access the meta element and then setAttribute to manipulate its contents.
来源:https://stackoverflow.com/questions/36655752/angular2-http-laravel-csrf-token