Search code examples
node.jsangulartypescriptaxiosangular-httpclient

REST call works with axios but not with HttpClient in an Angular 5 project


Service.ts code

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ClientService {

  constructor(private http: HttpClient) { }

  getClients() {
    return this.http.get<any>('http://localhost:8080/admin-api/client?count=15&page=0&q=', { withCredentials: true })
  }
}

Component.ts code

import { Component, OnInit } from '@angular/core';
import { LazyLoadEvent } from 'primeng/api'

import { ClientService } from '../../services/client.service';


@Component({
  selector: 'app-client',
  templateUrl: './client.component.html',
  styleUrls: ['./client.component.css']
})

export class ClientComponent implements OnInit {

constructor(private clientService: ClientService) { }

ngOnInit() {
    this.loading = true

    this.clientService.getClients().subscribe(data => {
      console.log(data)
    }, error => {
      console.log(error)
    })

  }
}

The error I get when I run this The browser console

I don't understand why the same request can succeed using axios but not with the HttpClient in Angular.


Solution

  • Apparently, Axios adds the "X-XSRF-TOKEN" header when it detects the "XSRF-TOKEN" cookie whereas the HttpClient in Angular doesn't.

    So you have to read the value of the "XSRF-TOKEN" cookie and set it as the header "X-XSRF-TOKEN" when sending your requests.