Angular2 Http Laravel CSRF Token

advertisements

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


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