How to setup express and node into an existing front-end only Angular 2 project?

坚强是说给别人听的谎言 提交于 2019-12-03 08:59:32
Joshua Terrill

The best way to setup a project that is built using angular-cli to use a nodejs/express backend is to simple create an express project that serves up a directory. In your client project, if it has been created using the angular-cli, you should be able to just type in ng build and it will compile everything into a dist directory.

From there, you can create an express server that serves up that dist directory like so:

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

The most simple server you could build would probably something like

var express = require('express')
var path = require('path');

var app = express()

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});

This will intercept all routes and redirect them to the index.html file in the dist/ folder that was created.

For more information on how to set this up and some more advanced settings, check out these links:

Just think about the dist/ folder as static files that will be served over an express server, and because routing and everything is handled through angular, you'll be set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!