Home >Backend Development >Golang >How to Resolve CORS Errors When Adding Authorization Headers in Angular?
Adding Authorization Header to Angular HTTP Requests
Problem:
An Angular application is experiencing a CORS error when adding an "Authorization" header to an HTTP request. The error is:
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
Best Practices:
In Angular 4 and later, it's recommended to use HTTP Interceptors to add authentication headers to requests and Guards to protect routes.
Angular Implementation:
To use an AuthInterceptor, create a TypeScript file (e.g., 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); } }
Next, register the interceptor in 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 Implementation:
On the Go side, ensure that the CORS middleware allows the necessary request headers:
headersOk := handlers.AllowedHeaders([]string{"*"}) originsOk := handlers.AllowedOrigins([]string{"*"}) methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
If the issue persists, carefully configure the CORS settings to match the headers sent by the client.
The above is the detailed content of How to Resolve CORS Errors When Adding Authorization Headers in Angular?. For more information, please follow other related articles on the PHP Chinese website!