首页 > 解决方案 > 结合 Angular 2 应用服务器和 REST 服务器模块

问题描述

我正在创建一个新的 Angular 4 应用程序。我已经按照它的官方教程https://angular.io/tutorial/

使用ng serve命令启动应用程序服务器。

我创建了一个单独的节点 js (+express) 服务器,它为不同端口上的主应用程序提供 REST 服务。

有没有办法从同一个 nodejs/express 服务器为主要的 Angular 应用程序提供服务,这样我就不必为应用程序使用两台服务器?

我使用了打字稿,如果我理解正确的话,它需要以某种方式编译成普通的 javascript,然后才能通过 nodejs 静态提供服务?

标签: javascriptnode.jsangular

解决方案


当然,只需使用 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);
});

不要忘记需要正确的库。


推荐阅读