首頁 >後端開發 >Golang >在 Angular 中新增授權標頭時如何解決 CORS 錯誤?

在 Angular 中新增授權標頭時如何解決 CORS 錯誤?

Susan Sarandon
Susan Sarandon原創
2024-12-28 22:00:18796瀏覽

How to Resolve CORS Errors When Adding Authorization Headers in Angular?

向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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn