javascript - 结合 Angular 2 应用服务器和 REST 服务器模块
问题描述
我正在创建一个新的 Angular 4 应用程序。我已经按照它的官方教程https://angular.io/tutorial/
使用ng serve
命令启动应用程序服务器。
我创建了一个单独的节点 js (+express) 服务器,它为不同端口上的主应用程序提供 REST 服务。
有没有办法从同一个 nodejs/express 服务器为主要的 Angular 应用程序提供服务,这样我就不必为应用程序使用两台服务器?
我使用了打字稿,如果我理解正确的话,它需要以某种方式编译成普通的 javascript,然后才能通过 nodejs 静态提供服务?
解决方案
当然,只需使用 ng build 并提供已构建应用程序的 dist 文件夹,甚至是 src。例子:
const staticFor = rel => express.static(path.resolve(__dirname, rel));
const app = express();
if (!config.production) {
app.use('/node_modules', staticFor('../node_modules'));
// In development we do not copy the files over, so map used path
}
app.use('/', staticFor('../dist/app'));
const appPath = path.resolve(
__dirname,
config.production ? '../dist/app/index.html' : '../src/app/index.html'
);
app.get('/yourAppPath/*', (req, res) => {
const markup = fs.readFileSync(appPath, 'utf8');
res.send(markup);
});
不要忘记需要正确的库。
推荐阅读
- react-native - 在反应本机类型的影子节点中更新属性“开始”时
- laravel - 如何解决 npm run dev
- wordpress - 在页面中进行某些更改时防止恢复为默认模板
- neo4j - 如何在 Neo4j 中获取从根到叶的所有路径(DFS 方式)并返回包含节点和关系的结果
- python - 如何在python中安排异步函数的执行并立即返回
- c - 在标准输入中使用 c 中的 read() 函数时区分剪贴板事件
- swift - 从代码覆盖范围中排除 SwiftUI 预览?
- javascript - 无论我尝试什么,JavaScript 函数都不起作用
- reactjs - React、动态 ANTD 选项卡和路由器
- flutter - 无法使用特定块的 vs 代码在飞镖(颤振)中折叠代码