Home > Backend Development > Golang > How to Resolve CORS Errors When Adding Authorization Headers in Angular?

How to Resolve CORS Errors When Adding Authorization Headers in Angular?

Susan Sarandon
Release: 2024-12-28 22:00:18
Original
852 people have browsed it

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
Copy after login

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);
  }
}
Copy after login

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,
    },
    ...
],

...
Copy after login

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"})
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template