我有一个问题,JWT令牌只在特定的API上才被添加到头中,我不知道为什么.. 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}`
      );
    }
  }
}

所以函数getBookmarks()可以工作,但是函数addToBookmark()不能.

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

推荐答案

http.post()的此签名与http.get()的签名不同.

  • 获得:get(url, options)

  • 发帖:post(url, body, options)

因此,在您的POST请求中,您在body参数中传递了options.

您可以通过添加身体数据进行修复:

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

Angular相关问答推荐

尽管有模拟间谍实现,规范文件仍调用真正的服务

CDK虚拟滚动由于组件具有注入属性而在滚动时看到错误的值

如何重新显示ngbAlert(Bootstrap widgest for Angular)消息后再次驳回它

Primeng:安装ANGLE 16.2.0版本

Ng serve不工作,没有错误或消息来显示问题所在

区分material 手风琴

Angular 15:在范围内提供相同标记时附加到提供的值

如何重置表单中的特定字段?

当我ng serve时,Angular CLI 提示TypeError: callbacks[i] is not a function

不再需要 core-js 了吗?

绑定 Angular material Select 列表

如何在插值中编写条件?

Angular2 测试 - 按 ID 获取元素

Angular2 CLI 错误@angular/compiler-cli包未正确安装

在Angular 4中以'yyyy-MM-dd'格式获取当前日期

Angular 2 应用程序中没有Access-Control-Allow-Origin标头

Mat-autocomplete - 如何访问选定的选项?

Angular 2:为什么在检索路由参数时使用 switchMap?

NPM 脚本 start退出,但未指示 Angular CLI 正在侦听请求

ngIf - 判断后表达式已更改