gpt4 book ai didi

Angular JWT Token 添加到 lazyUpdate 而不是 HttpHeaders 中的 header

转载 作者:行者123 更新时间:2023-12-05 03:18:50 26 4
gpt4 key购买 nike

我有一个问题,即 JWT token 未仅添加到特定 API 的 header 中,我不知道为什么......httpOptions.headers 的内容在每个函数中都不同,您可以在下面的屏幕截图中看到。

我的书签服务

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() - 错误 401 未经授权 enter image description here

addToBookmark() 函数中的控制台日志是: enter image description here

控制台登录getBookmarks()函数: enter image description here

最佳答案

http.post() 的签名不同于 http.get()

  • GET: get(url, options)

  • POST:post(url, body, options)

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

您可以通过添加 body 数据来修复:

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

关于Angular JWT Token 添加到 lazyUpdate 而不是 HttpHeaders 中的 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73598202/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com