首頁 > 後端開發 > Golang > 如何在 Go 中保護 Angular HTTP 請求並處理 CORS?

如何在 Go 中保護 Angular HTTP 請求並處理 CORS?

Patricia Arquette
發布: 2024-12-13 21:25:12
原創
363 人瀏覽過

How to Secure Angular HTTP Requests and Handle CORS in Go?

在Angular 和Go 中處理授權標頭

要將授權標頭加入Angular HTTP 請求,請考慮使用HTTP 攔截器。它們允許您向每個請求添加標頭,而 Guards 可用於路由保護。

Angular HTTP 攔截器範例:

// auth.interceptor.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
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 中的提供者:

// 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,
    },
    ...
],

...
登入後複製

轉CORS配置:

在Go中,確保您的 CORS 配置與客戶端發送的 HTTP 標頭匹配。如有必要,允許所有標頭:

headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
登入後複製

檢查 Chrome 開發者工具中的標頭,並考慮仔細重新配置 CORS 設定以與客戶端的標頭保持一致。這將解決您遇到的 CORS 問題。

以上是如何在 Go 中保護 Angular HTTP 請求並處理 CORS?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板