問題陳述:
嘗試向Angular 新增授權,但收到「請求的資源上不存在'Access-Control-Allow-Origin'標頭」錯誤。
解決方案:
在 Angular 應用程式中,建議使用 HTTP 攔截器來管理驗證標頭。 Guards 可以補充這種路由保護方法。
實作驗證攔截器:
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>> { if (AuthService.isLoggedIn()) { const token = AuthService.getToken(); req = req.clone({ setHeaders: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': `Bearer ${token}`, }, }); } return next.handle(req); } }
import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthInterceptor } from './auth/auth.interceptor'; ... providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, ... ], ...
headersOk := handlers.AllowedHeaders([]string{"*"})
以上是如何向 Angular HTTP 請求新增授權標頭並解決 CORS 問題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!