向Angular HTTP 請求添加授權標頭
問題:
Angular 應用程序正在遇到問題將「Authorization」標頭新增至HTTP 請求時出現CORS 錯誤。錯誤是:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403
最佳實踐:
在Angular 4 及更高版本中,建議使用HTTP Interceptors 向請求添加身份驗證標頭並進行保護路線。
角度實作:
要使用AuthInterceptor,請建立一個TypeScript 檔案(例如auth.interceptor.ts):
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Injectable } from '@angular/core'; 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: { 'Content-Type' : 'application/json; charset=utf-8', 'Accept' : 'application/json', 'Authorization': `Bearer ${AuthService.getToken()}`, }, }); return next.handle(req); } }
接下來,在app.module.ts中註冊攔截器:
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { AuthInterceptor } from '../auth/auth.interceptor'; ... imports: [ HttpClientModule, ... ], providers: [ { provide : HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi : true, }, ... ], ...
走吧實現:
在Go 端,確保CORS 中間件允許必要的請求標頭:
headersOk := handlers.AllowedHeaders([]string{"*"}) originsOk := handlers.AllowedOrigins([]string{"*"}) methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
如果問題仍然存在,請仔細配置CORS 設定以匹配標頭由客戶發送。
以上是在 Angular 中新增授權標頭時如何解決 CORS 錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!