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

angularjs node js server
angularjs node js example
angular 6 with node js example
angular 6 and node js integration
angular 7 with node js example
angular 2 with node js example
how to call node js api from '@angular 8
install angular

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

  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 ...

How can i run angular app on node server?, What language does node js use on the server side? And enjoy your app. If you want to serve React application using the Node server, then this article will help you a lot. If you’re interested in Node.js or JavaScript, then this link will help.

None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload. So this is how I solved it. Angular routing works even on full page reload.

function getRoot(request, response) {
   response.sendFile(path.resolve('./public/angular/index.html'));
}

function getUndefined(request, response) {
   response.sendFile(path.resolve('./public/angular/index.html'));
}

// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));

app.get('/', getRoot);
app.get('/*', getUndefined);

NO angular base-href rewrite is required! Just use ng build or ng build --prod.

What is node.js? Is it client side language or server side?, engine. It is an open source programming language that was developed by Ryan Dahl in 2009. Best practice is definitely to serve static files with something that is made to do so like nginx, a CDN, or another web server. In my opinion serving files from node.js is usually for small, low traffic websites. You can do exactly as you depicted. You can have your API on a different port.

Follow the Express node server with Angular 2 CLI document to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.

E.g.

Serve application with http://localhost:5000/app

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

or

Serve data from REST calls with http://localhost:5000/rest/contacts

app.get('/rest/user', function(req, res) {
    res.send({
        "id": 2,
        "name": "Jhon",
    })
});

An Introduction to Node.js, the Server Side JavaScript, is a front-end javascript framework which operates in the clients web browser. In this tutorial, we will take a look at creating server-applications with Node.js and the Express framework in relation to angular. We will not only create our first small server-application, but also create a functional REST-API to serve our data.

Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.

Here's the summary from beginning:

  1. npm install -g @angular/cli

  2. ng new PROJECT_NAME

  3. cd PROJECT_NAME

  4. npm install nodemon express cookie-parser body-parser morgan method-override --save

5.Create app.js:

var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();

console.log('——————————- Run on port '+ port);

/****************************** Router ***************************/
router.get('*', function(req, res){
    res.sendFile('index.html', { root: __dirname + '/' });
});

/****************************** /Router ***************************/

//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder

app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*

app.listen(port);
  1. Edit package.json file:

    { ... "scripts": { "start": "ng build; cp app.js dist/app.js; node dist/app.js", } ... }  

  2. npm start

This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app.

Do I need node.js to use Angularjs?, Now we can serve the app with express. $ node server.js. Going to http://​localhost:3000 should load the app, and http://localhost:  You can do this (1) before you're deploying your app to the server or (2) use a library like System.js that will transpile TypeScript on the fly. While (2) is definitely an option and the Angular CLI used it until recently, (1) is in my opinion the better option. Angular CLI switched to (1) and is now using webpack.

Here is full back end code which is working

const express = require('express');
var app = express();
var port = 9999;

function getRoot(request, response) {
    response.sendFile(path.resolve('./public/angular/index.html'));
 }

 function getUndefined(request, response) {
     response.sendFile(path.resolve('./public/angular/index.html'));
 }


 app.use(express.static('./public/angular'));

 app.get('/', getRoot);
 app.get('/*', getUndefined);

 // Start server
 app.listen(port, function () {
    console.log('server running at port: ' + port);
}); 

MEAN App with Angular 2 and the Angular CLI ― Scotch.io, Run your angular app on nodejs. We created our First let take a closer look how we configured our server.ts file But it work with ng serve. I have an application written on angularJS and built by grunt. Is there a way I can create a http server from node js and host it there. Please share any code snippet or document which would help.

Run your angular app on nodejs, Let's create a very simple Angular form application that stores user information The Proxy will re-route our API calls to a Node.js server to avoid the CORS exceptions. FormBuilder a service that helps making forms easier. Express.js is a web application framework for Node.js designed for building web applications, in this series of articles I will explain step by step how i realized an express server with some advanced functions that i use for my single page application made with Angular 7.

Simple Application with Angular 6 + Node.js & Express, Make sure your development environment includes Node.js® and an npm CLI includes a server, so that you can easily build and serve your app locally. I've written an Angular 5 application which gets its data from a node.js server. I have been able to deploy the application to my web server (which will run node.js at FastComet) but the server doesn't seem to work. I'm not sure if I have to deploy that separately, or if that gets included as part of the main ng build.

Setting up the local environment and workspace, One way is to build Angular with NodeJS or Java and another way is to build the angular and serve that static content with NGINX web server. To support both your API and your Angular app on the same express server, you should use Router Middleware to separate your Angular app from your API. Look at how the routes are structured in server.js and both /routes/api.js and /routes/api/xyz.js below. Will I still be able to minify my angular app before serving it from a node server?

Comments
  • You can create restful service using Node.js. And call that url from the angular2 app.
  • Answer of @JohnSiu handle now browser url entered manually (Default route)
  • Yes, possible solution is rendering the index.html in build directory as static content. If there are routing it the angular2 app, it can be navigated through links in the page, but can't by changing the browser url
  • @yohan it is possible to handle angular2 routing by adding custom static route pointing to the index page in the nodejs app.
  • @yohan I think the base href is automatically added when ng2 cli generate the project.
  • we can specify it by ng build --base-href /myUrl/ when building. Even if it is corrected we can't navigate by changing url in the browser.
  • @Yohan To allow support of browser url, simply add this .use(function(req, res) { res.sendFile(html + 'index.html'); })
  • from next time please comment full code or provide an online link where whole code is structured
  • @Maddy There is no need to post a full stack example on a node.js specific question, especially in this simple case. The basic node setup can be obtained from the docs.
  • This is also serving angular2 app as a static content, the matter is, we can't navigate in the app routes by changing url
  • Off-course u can navigate through url, since the entire application is loaded by index.html. check with angular-cli 1.0.0.19
  • Works well! Thanks a lot! Only need to change starts in package.json -> "scripts": {"start": "ng build && cp app.js dist/app.js && node dist/app.js"}. Note for windows "scripts": {"start": "ng build && copy app.js dist/app.js && node dist/app.js"}