Home > other >  Angular JWT Token is added to lazyUpdate instead of headers in HttpHeaders
Angular JWT Token is added to lazyUpdate instead of headers in HttpHeaders

Time:09-05

I have a problem that JWT token is not added to headers only on specific API and I don't know why.. The content of httpOptions.headers is different in each function as you can see in the screenshots below.

My bookmarks service

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { UserAuthService } from '../user-auth/user-auth.service'; 
import { Bookmark } from 'src/app/models/api/bookmarks/Bookmark';

let httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }),
};

@Injectable({
  providedIn: 'root',
})
export class BookmarksService {
  jwtToken: string | null = this.userAuthService.getJwtToken();

  private apiUrl: string = environment.apiUrl;

  constructor(
    private http: HttpClient,
    private userAuthService: UserAuthService
  ) {}

  // Get bookmarks
  getBookmarks(): Observable<Bookmark> {
    this.addJwtToHeaders();

    const url: string = `${this.apiUrl}/bookmark/`;
    return this.http.get<Bookmark>(url, httpOptions);
  }

  addToBookmark(id: string): Observable<any> {
    this.addJwtToHeaders();
    console.log(httpOptions.headers);

    const url: string = `${this.apiUrl}/bookmark_add/${id}/`;
    return this.http.post<any>(url, httpOptions);
  }

  addJwtToHeaders(): void {
    const auth = httpOptions.headers.get('Authorization');
    if (!auth) {
      if (!this.jwtToken) return;
      httpOptions.headers = httpOptions.headers.append(
        'Authorization',
        `Token ${this.jwtToken}`
      );
    }
  }
}

So the function getBookmarks() works, but function addToBookmark() doesn't.

getBookmarks() enter image description here

addToBookmark() - error 401 Unauthorized enter image description here

The console log in the addToBookmark() function is: enter image description here

And the console log in the getBookmarks() function: enter image description here

CodePudding user response:

This signature for http.post() is different from http.get().

  • GET: get(url, options)

  • POST: post(url, body, options)

So in your POST request, you are passing your options in the body parameter.

You can fix by adding your body data:

this.http.post<any>(url, body, httpOptions)
  • Related