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