【发布时间】: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