本文介绍了在 Angular Universal 中的应用程序模块中获取 serverURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到错误 Http urls must be absolute.这是因为我使用这个 http.get('/env')
应用程序在不同的环境中运行,因此 url 可以更改.所以我不能使用它,例如 http.get('http://test.com/env')
我也不能使用 window.location.origin.因为我使用的是通用的.我该如何解决这个问题?
I am getting the error Http urls has to be absolute. It's because iam using this http.get('/env')
the app is ran in different environments so the urls can change. So I can't use this for example http.get('http://test.com/env')
I also cant use window.location.origin. bacause I am using universal. How do I solve this?
import { HttpModule, Http } from '@angular/http';
providers: [
RootController,
AuthService,
AuthGuard,
HttpRequestService,
{
'provide': APP_INITIALIZER,
'useFactory': (http: Http) => {
return () => {
return new Promise((resolve, reject) => {
const req = http.get('/env').pipe(map(env => env.json())).subscribe(config => {
CONFIG.ORIGIN = config.ORIGIN;
CONFIG.API_URL = config.API_URL;
CONFIG.BASE_HREF = config.BASE_HREF;
CONFIG.SOCIAL = config.SOCIAL;
console.log(CONFIG);
resolve(CONFIG);
}, error => {
reject(error);
});
});
};
},
'deps': [Http],
'multi': true
},
],
bootstrap: [AppComponent]
server.ts
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 3000;
const DIST_FOLDER = join(process.cwd(), 'dist');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node server listening on http://localhost:${PORT}`);
});
推荐答案
尝试这样的事情
- 提供来自angular通用服务器的服务器url
server.ts
编辑这里是使用express引擎的版本
Edit Here is the version using express engine
//...
// All regular routes use the Universal engine
app.get('*', (req, res) => {
//let serverUrl = req.protocol + '://' + req.get('host');
let serverUrl = `http://localhost:${PORT}`;
res.render('index',
{ req,
res,
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP),
{
provide: 'serverUrl',
useValue: serverUrl
}
]
});
});
结束编辑
server.ts
(不使用快递引擎)
app.engine('html', (_, options, callback) => {
let serverUrl = options.req.protocol + '://' + options.req.get('host');
renderModuleFactory(AppServerModuleNgFactory, {
//...
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP),
{
provide: 'serverUrl',
useValue: serverUrl
}
]
}).then(html => {
//...
});
});
- 使用提供的值角边
app.module.ts
import {Optional, InjectionToken} from '@angular/core';
import { HttpModule, Http } from '@angular/http';
const ServerUrl = new InjectionToken('serverUrl');
//...
providers: [
RootController,
AuthService,
AuthGuard,
HttpRequestService,
{
'provide': APP_INITIALIZER,
'useFactory': (http: Http, serverUrl: string) => {
return () => {
return new Promise((resolve, reject) => {
//serverUrl will be empty client side, and contain server URL when using angular universal
const req = http.get((serverUrl || '') + '/env').pipe(map(env => env.json())).subscribe(config => {
CONFIG.ORIGIN = config.ORIGIN;
CONFIG.API_URL = config.API_URL;
CONFIG.BASE_HREF = config.BASE_HREF;
CONFIG.SOCIAL = config.SOCIAL;
console.log(CONFIG);
resolve(CONFIG);
}, error => {
reject(error);
});
});
};
},
'deps': [Http, [new Optional(), ServerUrl] ], //<= optional dependency
'multi': true
},
],
bootstrap: [AppComponent]
这篇关于在 Angular Universal 中的应用程序模块中获取 serverURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!