Angular 6-为什么生产版本中缺少Bearer令牌? (在开发版本中工作正常) [英] Angular 6 - Why is Bearer Token missing in production build? (works fine in dev build)

查看:95
本文介绍了Angular 6-为什么生产版本中缺少Bearer令牌? (在开发版本中工作正常)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 6和HTTP拦截器,该拦截器配置为将承载令牌应用于传出请求.

I'm using Angular 6 with an HTTP Interceptor configured to apply bearer token to outgoing requests.

  • 在开发版本(ng serve)中,应用了令牌,并且一切正常. :-)

  • In the dev build (ng serve), the token is applied and everything works fine. :-)

在生产版本(ng serve --prod)中,没有承载令牌的情况下发出了请求. :-(

In the production build (ng serve --prod) the request is sent out without bearer token. :-(

在prod版本中,通过在应用标头后将其转储到控制台,我已经验证了标头已被应用.

In the prod build, I have verified the header is being applied, by dumping the headers to the console after applying them.

我不知道为什么将它们从http请求中排除.

I have no idea why they are excluded from the http request.

我的environment文件中没有任何差异.

There are NO differences in my environment files.

我还要看什么?

该如何解决?

起初,我认为这是我的本地环境和暂存环境之间的问题,但是后来我尝试在本地运行ng serve --prod并看到了相同的结果.

At first I thought this was an issue between my local environment and my staging environment, but then I tried running ng serve --prod locally and saw the same results.

总而言之,除了一个是生产版本,一个是开发版本之外,所有内容都是相同的.

All that to say, everything is identical except one being a production build and one being a dev build.

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);
    }
}

这是我在控制台中看到的内容:

Here's what I see in the console:

app.module.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 {
}

推荐答案

我用StackBlitz编写了这个应用程序,当我在ng serve --prod本地运行它时,它运行良好.

I wrote this app in StackBlitz, and it's working fine when I run it locally with ng serve --prod.

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

下载并运行它,以查看是否仍在网络标签中找到undefined.如果您可以看到标头已正确发送,那么您的代码中肯定有一些有趣的东西.

Download it and run it to see if you're still getting undefined in your network tab. If you can see the header properly being sent, then there's definitely something funny in your code.

尝试下面的提示:

1-尝试运行`ng serve --port = aDifferentPort//像2098一样

1- try running `ng serve --port=aDifferentPort // like 2098

也许该端口上正在运行某些东西并发送auth标头

Maybe there's something running on that port and sending auth header

2-尝试将AOT设置为false,想不出为什么会导致任何问题

2- Try with AOT false, can't think of why that would cause any issue

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

3- Make sure your browser doesn't have any extension that overrides the Auth header or try other browsers

4- 关闭其他HTTP拦截器,也许其中一个拦截器执行了意外的操作

5- 将标头名称从Authorizaion更改为MyAuthorization,查看您是否仍未定义,如果未定义,则被某些内容覆盖,请检查您的package.json并确保您不在生产服务上运行任何其他操作.

5- Change the header name from Authorizaion to MyAuthorization, see if you're still getting undefined, if you don't, then it's being overridden by a something, check your package.json and make sure you're not running anything else on the production serve.

6- 完全关闭JwtInterceptor,然后尝试将授权标头附加到您的HTTP请求,看看您是否仍在获得undefined.

6- Turn off the JwtInterceptor altogether and try attaching the authorization header to your HTTP request, see if you're still getting undefined.

7-如果没有帮助,您确实需要发送更多代码给我们:)

7- If none helped, you really need to send more code to us :)

这篇关于Angular 6-为什么生产版本中缺少Bearer令牌? (在开发版本中工作正常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆