且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将授权标头添加到Angular http请求?

更新时间:2021-07-07 06:00:30

关于在 Angular> 4 中处理身份验证标头的***方法,***使用
Http Interceptors将它们添加到每个请求中,然后使用
Guards用于保护您的路线.

Regarding the best way of handling Authentication headers in Angular > 4 it's best to use
Http Interceptors for adding them to each request, and afterwards using
Guards for protecting your routes.

这是我在应用程序中使用的AuthInterceptor的完整示例:

Here's a full example of an AuthInterceptor that I'm using in my app:

auth.interceptor.ts

auth.interceptor.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';

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中将拦截器注册为提供程序:

You'll need to register your interceptor in the app.module as a provider:

app.module.ts

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 这些标题.
您应该尝试的第一件事就是允许所有人:

Regarding the Go's side of things, this is most likely a case of mismatch between
Request Headers you're sending and the headers CORS allow.
First thing you should try is allowing all of them:

headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

如果问题消失了,请尝试根据客户发送的内容仔细构造您的 CORS .

And if the problem goes away try carefully structuring your CORS one by one to what your client is sending.