问题陈述:
尝试向 Angular HTTP 添加授权标头请求,但收到“请求的资源上不存在‘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, }, ... ], ...
关于Go HTTP 请求:
错误表明请求标头和 CORS 配置之间可能存在不匹配。实施以下步骤:
headersOk := handlers.AllowedHeaders([]string{"*"})
以上是如何向 Angular HTTP 请求添加授权标头并解决 CORS 问题?的详细内容。更多信息请关注PHP中文网其他相关文章!