我已经查看了关于如何将SSR(服务器端渲染(添加到现有angular CLI&Express项目。
我可以用SSR运行节点,但我不能调用API。我希望运行一个节点进程,该进程可以使用API调用提供静态文件(Angular with SSR(和动态内容,这些调用使用KNEX访问SQLITEDB。
这是我的服务器.js文件
// 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(), 'bin/dist');
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./bin/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, ''));
// import * as apiS from './server/index';
// apiS.load(app);
// TODO: implement data requests securely
// app.get('/api/*', (req, res) => {
// res.status(404).send('data requests are not supported');
// });
import * as LoadRoutes from './server/boot/routes';
LoadRoutes.load(app);
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, '')));
// 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}`);
});
是否可以从同一个节点进程完成SSR+neneneba API调用?如果可以,这里的帖子可以回答吗?
它已经存在了。只需取消注释这些行,并使用Express路由器扩展API路由:
app.get('/api/*', (req, res) => {
res.status(404).send('data requests are not supported');
});
改为使用路由器文件:
app.use('/api/*', appRoutes);
每个以api/开头的URL都将由后端api提供服务。