Problem Statement:
Attempting to add an authorization header to an Angular HTTP request, but receiving a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error.
Solution:
In Angular applications, HTTP interceptors are recommended for managing authentication headers. Guards can complement this approach for route protection.
Implementing Authentication Interceptors:
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, }, ... ], ...
Regarding Go HTTP Request:
The error suggests a potential mismatch between request headers and CORS configuration. Implement the following steps:
headersOk := handlers.AllowedHeaders([]string{"*"})
The above is the detailed content of How to Add Authorization Headers to Angular HTTP Requests and Resolve CORS Issues?. For more information, please follow other related articles on the PHP Chinese website!