Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 550
YohanK Avatar asked Oct 04 '16 06:10

YohanK


People also ask

Where can I host my Angular app?

Because these files are static, you can host them on any web server capable of serving files; such as Node. js , Java, . NET, or any backend such as Firebase, Google Cloud, or App Engine.

How do I run an Angular project on shared hosting?

import { LocationStrategy, PathLocationStrategy } from '@angular/common'; Now execute ng build --prod once more and upload the new distribution files to your shared server — everything should now work! That is all you need to begin working with Angular on your very own shared hosting server.


1 Answers

  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 ...
like image 94
John Siu Avatar answered Sep 21 '22 13:09

John Siu