代码之家  ›  专栏  ›  技术社区  ›  BizzyBob

角度6-为什么在生产构建中缺少承载令牌(在dev-build中运行良好)

  •  20
  • BizzyBob  · 技术社区  · 7 年前

    我使用的是Angular6,配置了一个HTTP拦截器,将承载令牌应用于传出请求。

    • 在开发版本中( ng serve :-)

    • ng serve --prod )请求在没有承载令牌的情况下发出。 :-(

    我不知道为什么他们被排除在http请求之外。

    我的生活没有什么不同 environment 文件夹。

    我还应该看什么?

    missing bearer token

    ng serve--生产 在当地也看到了同样的结果。

    jwt拦截器:

    import { Injectable } from '@angular/core';
    import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
    import { Observable } from 'rxjs';
    
    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
            // add authorization header with jwt token if available
            let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
            if (currentUser && currentUser.token) {
                request = request.clone({
                    setHeaders: {
                        Authorization: `Bearer ${currentUser.token}`
                    }
                });
                console.log('headers:', request.headers); // <---- I can see headers in console output
            }
    
            return next.handle(request);
        }
    }
    

    以下是我在控制台中看到的内容: screenshot of console output

    应用模块ts

    import { HttpClientModule, HttpClient, HttpInterceptor } from '@angular/common/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { HTTP_INTERCEPTORS } from '@angular/common/http';
    import { PortalModule } from '@angular/cdk/portal';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    
    import { JwtInterceptor } from './jwt-interceptor';
    import { ENV } from '../environments/environment';
    import { AppComponent } from './app.component';
    import { AppRoutingModule } from './app-routing.module';
    ... 
    import { myApiService } from './services/my-api.service';
    import { myModalComponent } from './_components/my-modal/my-modal.component';
    import { myModalService } from './services/my-modal.service';
    
    import { AngularLaravelEchoModule, PusherEchoConfig, EchoInterceptor } from 'angular-laravel-echo/angular-laravel-echo';
    
    export const echoConfig: PusherEchoConfig = {
        userModel: 'App.User',
        notificationNamespace: 'App\\Notifications',
        options: {
            broadcaster: 'pusher',
            key: ENV.pusherConfig.key,
            cluster: ENV.pusherConfig.cluster,
            host: ENV.apiRoot,
            authEndpoint: ENV.apiRoot + '/broadcasting/auth',
        }
    };
    
    @NgModule({
        declarations: [
            AppComponent,
            ...
        ],
        imports: [
            BrowserModule,
            HttpClientModule,
            BrowserModule,
            AppRoutingModule,
            FormsModule,
            ReactiveFormsModule,
            PortalModule,
            AngularLaravelEchoModule.forRoot(echoConfig)
        ],
        providers: [
            myApiService,
            myModalService,
            {
                provide: HTTP_INTERCEPTORS,
                useClass: JwtInterceptor,
                multi: true,
            },
            {
                provide: HTTP_INTERCEPTORS,
                useClass: EchoInterceptor,
                multi: true
            }
        ],
        bootstrap: [AppComponent],
        entryComponents: [ 
            myModalComponent
        ]
    })
    
    export class AppModule {
    }
    
    6 回复  |  直到 7 年前
        1
  •  3
  •   Milad    7 年前

    我在StackBlitz中编写了这个应用程序,当我在本地用 ng serve --prod

    https://stackblitz.com/edit/angular-yzckos

    下载并运行它,看看你是否仍然得到 undefined 在“网络”选项卡中。如果你能看到正确发送的头,那么你的代码中肯定有一些有趣的东西。

    1-尝试运行`ng serve--port=aDifferentPort//like 2098

    可能有什么东西在那个端口上运行,正在发送auth头

    3-确保您的浏览器没有任何覆盖验证头的扩展,或尝试其他浏览器

    4-

    5- 将标题名称从更改为 Authorizaion MyAuthorization package.json 确保你没有在生产服务上运行任何其他东西。

    关掉电源 JwtInterceptor 然后尝试将授权标头附加到 HTTP 请求,看看你是否还在 .

    7-如果没有帮助,您真的需要向我们发送更多代码:)

        2
  •  0
  •   Anjana Silva    7 年前

    在生产环境中,服务器完全忽略 Authorization 标题。角度6发送 授权

    最后,为了让它工作,我不得不使用一个不同的头参数,比如 Php-Auth-Digest

    request = request.clone({
        setHeaders: {
          "Php-Auth-Digest": `Bearer ${currentUser.token}`,
        }
      });
    

    作为解决方法,请尝试更改头参数名称。

    干杯!

        3
  •  0
  •   Minu    7 年前

    put(path: string, body: Object = {}): Observable<any> {
    return this.http.put(`${environment.api_url}${path}`, body, { headers: 
         this.setHeaders() })
         .map((res: Response) => {
            return res;
         });
    }
    
    private setHeaders(): HttpHeaders {
        const headersConfig = {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer ' + this.oauthService.getAccessToken()
        };
        return new HttpHeaders(headersConfig);
    }
    

    拦截器只有

    request.clone() 
    
        4
  •  0
  •   Heehaaw    7 年前

    您可以尝试手动克隆邮件头 request.clone()

    export class HttpHeaderInterceptor implements HttpInterceptor {
      // ...
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // ...
        const clonedRequest = req.clone({ 
          headers: req.headers.set('Authorization', 'Bearer ' + currentUser.token) 
        });
        return next.handle(clonedRequest).pipe(
          catchError(err => { /* Error handling here */ })
        );
      }
    }
    

    希望这有点帮助:-)

        5
  •  0
  •   Rahul    7 年前

    我有一个想法-但我不确定它是否有效-请检查

    HttpHeaders

    private getHeaders(): HttpHeaders {
        let headers = new HttpHeaders();
        headers = headers.append("Content-Type", "application/json");
        return headers;
      }
    

    因为,我附加了新的头并将对象分配给原始对象并返回了对象-这在prod和dev build中都很好地工作

    HttpInterceptor 或者试着改变现状 setheaders 具有 headers 如下所述样品

    if (currentUser && currentUser.token) {
                request = request.clone({
                    headers: new HttpHeaders({
                        Authorization: `Bearer ${currentUser.token}`
                    })
                });
                console.log('headers:', request.headers); 
            }
    

    我相信这将解决你的问题,在两个版本-尝试,让我知道如果它不工作-希望它能工作谢谢-快乐的编码!!

        6
  •  -2
  •   Max    7 年前

    试试这个

    if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
            console.log('headers:', request.headers); // <---- I can see headers in console output
        }
    if (typeof $ != 'undefined') {
        $.ajaxSetup({
          beforeSend: function (xhr: any) {
            xhr.setRequestHeader('Authorization', 'Bearer ' + currentUser.token);
          }
        });
      }
        return next.handle(request);