Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js as http server and host angularJS SPA

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

like image 511
dhana Avatar asked Jul 17 '15 05:07

dhana


People also ask

CAN node and AngularJS work together?

NodeJS takes part in loading the AngularJS application with all the dependencies, such as CSS files and JS files in the browser. For loading all the assets of Angular and accepting all the API calls from the AngularJS applications, NodeJS is generally used as a web server.

Can you create an HTTP web server with NodeJS?

The Node. js framework can be used to develop web servers using the 'http' module. The application can be made to listen on a particular port and send a response to the client whenever a request is made to the application.

Is NodeJS a HTTP server?

Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP).

Which is better Angular or NodeJS?

Node. js is more preferable when faster and scalable web development is needed. It is usually used for building small-sized projects. Angular is preferred when real-time applications, for example, chat apps, or instant messaging are needed.


2 Answers

  1. (simplest) if you don't have any server side logic, you can simply serve client side AngularJS/HTML/css via http-server module from npm. https://www.npmjs.com/package/http-server Just install it via $>npm install -g http-server and go to your client folder, type http-server and hit enter.

  2. If you have server side code written, (ExpressJS or restify web api) then use $>nodemon server.js

  3. If you are looking at options for production applications, consider forever/pm2 https://www.npmjs.com/package/pm2 https://www.npmjs.com/package/forever

like image 122
Anand Avatar answered Sep 20 '22 07:09

Anand


Use the following code in your app.js file.

var express = require('express');

var path = require('path');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

/* GET home page. */
app.get('/', function(req, res, next) {
  //Path to your main file
  res.status(200).sendFile(path.join(__dirname+'../public/index.html')); 
});

module.exports = app;

Run the app.js file using node app.js

like image 26
Ajay Kumar Avatar answered Sep 20 '22 07:09

Ajay Kumar