首页 >后端开发 >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