如何向Angular HTTP 請求添加授權標頭
當嘗試將Angular 應用程式連接到Go API 時,必須包含授權HTTP 請求中的標頭。這保證了客戶端和伺服器之間的通訊安全。以下示範如何實現此目的:
Angular 實作:
在Angular 4 及更高版本中,建議使用HTTP 攔截器將授權標頭一致地應用於請求。以下是攔截器的範例:
import { Injectable } from '@angular/core'; import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { req = req.clone({ setHeaders: { Authorization: `Bearer ${AuthService.getToken()}`, }, }); return next.handle(req); } }
此攔截器可以在Angular 模組註冊:
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; ... providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, ], ...
Go 實作:
Go 實作:headersOk := handlers.AllowedHeaders([]string{"*"}) originsOk := handlers.AllowedOrigins([]string{"*"}) methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
以上是如何保護 Angular-Go API 通訊的安全性:新增授權標頭?的詳細內容。更多資訊請關注PHP中文網其他相關文章!