angularlaravelcsrf

Pass csrf meta tag with angular 4 when using laravel as API only


I'm using Laravel 5.5 and Angular 4. Laravel is only as an API. I'm trying to pass the data from a form and I can't pass the csrf token. Here's my service:

import { ElementRef, Injectable, Injector, Renderer2, ViewChild } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Link } from './link.model';
import 'rxjs/Rx';
import { RequestOptions } from '@angular/http';

@Injectable()
export class LinkService {

    constructor(private http: HttpClient) {

    }

    createLink(link): Observable<any> {
    //links param is the data from the form
      
        let url = 'http://127.0.0.1:8000/links';
        return this.http
            .post(url, link)
            .map(response => {
                console.log(response);
            })
    }
}

I've removed the VerifyCsrfToken middleware from the App/Kernel.php so there is no error now. But if somebody knows if it is possible to pass it, please let me know.


Solution

  • The VerifyCsrfToken Middleware requires a Laravel session and a X-CSRF-TOKEN header in each POST request. By deafult laravel sends a X-XSRF-TOKEN cookie with GET responses so you can take the value and implement the Angular HttpInterceptor to set the header in your requests.

    I hope it helps.