在我请求/category服务的地方,我用angular2创建了一个angular通用应用。
this.hsService.getCategories(AppConstants.BASE_URL_GET_CATGORIES).subscribe(
resp => {
if (resp !== null) {
console.log('response is not null');
}else {
console.log('response is null');
}
},
err => {
console.log('error');
that.categories = that.Categories();
}
);
但是我在error下面得到了这个错误。但是不明白为什么?
错误:通过服务器上的Http请求的URL必须是绝对URL。网址: /category at validateRequestUrl (D:\Myprojects\angular universal\ciel\node_modules\@angular\platform-server\bundles\platform-server.umd.js at new /category) (D:\Myprojects\angular universal\ciel\node_modules\@angular\platform-server\bundles\platform-server.umd.js:226:9) at ZoneMacroTaskBackend.createConnection (D:\Myprojects\angular universal\ciel\node_modules\@angular\platform-server\bundles\platform-server.umd.js:262:16) (D:\Myprojects\angular universal\ciel\node_modules\@angular\http\bundles\http.umd.js:1833:20) at Http.request (D:\Myprojects\angular universal\ciel\node_modules\@angular\http\bundles\http.umd.js:1957 at Http.get (D:\Myprojects\angular Myprojects:21)在n.getCategories (D:\Myprojects\angular universal\ciel\dist-server\main.bundle.js:1:24428) at n.XV61.n.ngOnInit (D:\Myprojects\angular universal\ciel\dist-server\main.bundle.js:1:26301) at n.XV61.n.ngOnInit (D:\Myprojects\angular Myprojects at checkAndUpdateDirectiveInline(D:\Myprojects\angular universal\ciel\node_modules\@angular\core\bundles\core.umd.js:10875:19)
有人能帮我吗?
发布于 2018-05-28 16:45:17
在服务器端呈现中,任何HTTP调用都需要绝对URL。
您可以选择
在answers to this问题中,有多个解决方法可供选择2。
我个人建议配置一个注入令牌,为您提供服务器的来源,并使用HTTP拦截器将其添加到基本URL:
添加HTTP拦截器类:
import { Injectable, Inject, Optional } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject('serverUrl') protected serverUrl: string) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
const serverReq = !this.serverUrl ? req : req.clone({
url: `${this.serverUrl}${req.url}`
});
return next.handle(serverReq);
}
}
将其添加到服务器端模块的提供者数组中:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: UniversalInterceptor,
multi: true
}
在您的服务器端配置(本例中为express)中,为令牌提供服务器的源URL:
let protocol = 'http';
if (process.env.NODE_ENV == 'production') {
protocol = 'https'
}
app.engine('html', (_, options, callback) => {
let engine = ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP),
{
provide: 'serverUrl',
useValue: `${protocol}://${options.req.get('host')}`
}
]
});
engine(_, options, callback)
})
发布于 2018-05-28 13:57:16
错误:通过服务器上的Http请求的URL必须是绝对URL。
看起来AppConstants.BASE_URL_GET_CATGORIES
是undefined
或无效的http
URL。
我认为你需要注入原始url来创建绝对路径。
export function createTranslateLoader(http: Http, @Inject('AppConstants.BASE_URL_GET_CATGORIES') originUrl: string) {
return new TranslateHttpLoader(http, originUrl);
}
https://stackoverflow.com/questions/50553444
复制相似问题