How to serve an angular2 app in a node.js server

YohanK picture YohanK · Oct 4, 2016 · Viewed 27.6k times · Source

I'm building a web app using Angular2, to create the project I'm using Angular2 CLI webpack. Angular2 app uses other external packages also (Eg: Firebase). In addition to that, I need to create a REST API running on node.js

How can I serve both of Angular2 app and REST API using node.js server

Answer

John Siu picture John Siu · Oct 4, 2016
  1. Use ng build to build your app into build directory.
  2. Create nodejs app to server the build directory as static content, then create route for api.

Following is an example of nodejs app using express that will serve the Angular2 app:

/*
Put content of angular2 build into 'public' folder.
*/
const html = __dirname + '/public';

const port = 4000;
const apiUrl = '/api';

// Express
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
var app = express();

app
    .use(compression())
    .use(bodyParser.json())
    // Static content
    .use(express.static(html))
    // Default route
    .use(function(req, res) {
      res.sendFile(html + 'index.html');
    })
    // Start server
    .listen(port, function () {
        console.log('Port: ' + port);
        console.log('Html: ' + html);
    });

// continue with api code below ...