【问题标题】:Cors issue on ngx-translate of externally loaded js in Angular projectAngular 项目中外部加载的 js 的 ngx-translate 的 Cors 问题
【发布时间】:2020-06-16 01:22:44
【问题描述】:

首先介绍一下上下文:我们有一个 Angular 项目(称为“项目 X”),它有自己的 json 翻译文件(加载了 ngx-translate)。然后将该项目作为 Angular Elements 移植(整个移植到单个 js 文件,称为“my-lib.js”)。另一个项目(“项目 Y”)动态加载此脚本,因此项目 X 的​​ Angular 元素可以在其中使用。项目 Y 还使用了它自己的通过 ngx-translate 加载的 json 翻译文件。

项目 X 构​​建到 /dist,项目 X 的​​ json 翻译文件复制到 /dist/i18n 中。然后,此 /dist 文件夹在端口 3003(即http://localhost:3003)上与 lite-server 一起提供。在 bs-config.json 文件中指定了此端口以及“cors: true”:

{
    "port": 3003,
    "files": ["./src/**/*.{html,htm,css,js,json}"],
    "server": { "baseDir": "./dist" },
    "cors": true
}

然后项目 Y 也被服务(“ng serve”)。默认语言为英语。所以项目 Y 中的 en.json 文件被正确加载了!但是......项目X的en.json文件不是......“en.json”托管在http://localhost:3003/i18n/en.json上,我可以通过url访问它。但在项目 Y 中,我收到一个 cors 错误,如下所示:

在 AppModule 中导入项目 X ngx-translate 模块如下:

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, environment.production ? '/objt-lib/assets/i18n/' : (environment.staging ? 'http://localhost:3003/i18n/' : '/assets/i18n/'), '.json');
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserTransferStateModule,
    BrowserModule,
    AppRoutingModule,
    ...
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient],
      }
    }),
    BrowserAnimationsModule
  ],
  providers: [
    ...
  ],
  bootstrap: environment.production ? [] : [AppComponent]
})
// export class AppModule { }
export class AppModule implements DoBootstrap {
   ....
}

在项目 Y 中导入如下:

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, '/assets/i18n/', '.json');
}

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    AppRoutingModule,
    ...
    BrowserAnimationsModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    HttpClientModule
  ],
  providers: [
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
  }
}

为什么会出现 cors 错误? 提前致谢!

【问题讨论】:

    标签: angular cors ngx-translate angular-elements lite-server


    【解决方案1】:

    幸运的是自己找到了答案!我似乎有一个 HttpInterceptor 添加了额外的 HttpHeaders,这就是它发送预检请求的原因(这导致了 cors 问题)!当它是一个简单的 GET 请求时不会发送预检请求,但是当您向请求中添加某些 HTTP 标头时,浏览器会发送一个预检请求。 所以 TLDR:从 HttpInterceptor 中删除了额外的 http 标头,瞧!像魅力一样工作:-)!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 2019-07-02
      • 2018-10-16
      • 2017-02-09
      • 1970-01-01
      相关资源
      最近更新 更多