Implementing Angular HttpClient with CSRF Token
Show a code example where Angular's HttpClient is used to send a POST request that includes a CSRF token fetched from cookies.
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient, private cookieService: CookieService) { }
// Function to send a POST request including the CSRF token
sendDataWithCsrf(url: string, data: any) {
// Get the CSRF token from the cookie
const csrfToken = this.cookieService.get('XSRF-TOKEN');
// Create request headers including the CSRF token
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'X-XSRF-TOKEN': csrfToken
});
// Send the POST request with the headers
return this.http.post(url, data, { headers: headers });
}
}
This code defines an Angular service that uses the HttpClient to send a POST request, including a CSRF token which is retrieved from cookies using the ngx-cookie-service library. HttpHeaders are used to attach the CSRF token to the request headers, and the HttpClient's post method is called with the target URL, data to send, and the constructed headers.