0

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

2 Answers 2

4

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!!

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thanks Benjamin. The meta tag syntax is Laravel and it generates the token. I updated the question with a function to pull the token to Angular2 so I now have the token in Angular I just don't know how to pass it with the post request back to Laravel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.