AngularJS , Node.js, ExpressJS application integration issue - node.js

I have created a RESTful service using Node.js and ExpressJS. Now I would like to implement View part. For this I have chosen AngularJS.
Problem here is, I am not sure how to organize folder structure and how to integrate AngularJS with Node.js and ExpressJS.
I watched this video, but for this no sample source code available.
Let's Get CRUDdy: AngularJS and Node.js Ferrari Example
Project folder structure
ExpressJS file
var express = require('express'),
http = require('http'),
path = require('path'),
photos = require('./routes/photos');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
app.use(app.router);
});
app.get('/photos', photos.findAll);
app.get('/view1', photos.index);
AngularJS:
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
When I hit url http://www.domain/view1, it should display index.html. But I am getting 404 code.
Please let me know if you need more info on it.

If you're using AngularJS to implement a single-page experience then you should serve the same front-end code every time, and then have AngularJS take over processing the URLs and displaying the content.
Remember that you are managing two routing systems. One for the front-end and one for the backend. Express routes map to your data, usually returned in JSON format. (You can also render html directly, see Option #1.) Angular routes map to your templates and controllers.
Option #1:
Set static folder to serve front-end code (HTML/CSS/JS/AngularJS).
app.use(express.static(__dirname + '/public'));
Look at these for sample code:
https://github.com/btford/angular-express-seed
https://github.com/btford/angular-express-blog
Directory Structure:
public/
index.html
js/
angular.js
css/
partials/
partial1.html
partial2.html
app/
node_modules/
routes/
web-server.js
Option #2:
Serve the front-end code and backend code on separate servers.
This doesn't mean you have to have two machines.
Here is a workable set up on your local machine with Apache:
Directory Structure:
public/
index.html
js/
angular.js
css/
partials/
partial1.html
partial2.html
node/
app/
node_modules/
routes/
web-server.js
Set up hosts file
127.0.0.1 domain.dev
Set up http://domain.dev/ to point to public/
<VirtualHost *:80>
DocumentRoot "/path/to/public"
ServerName domain.dev
ServerAlias www.domain.dev
</VirtualHost>
Set up http://api.domain.dev/ to point to the running node web-server
<VirtualHost *:80>
ServerName api.domain.dev
ProxyPreserveHost on
ProxyPass / http://localhost:3000/
</VirtualHost>
(Adapted from: http://www.chrisshiplet.com/2013/how-to-use-node-js-with-apache-on-port-80/)
Start (or restart) Apache and run your node server:
node web-server.js
Angular Routes:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives',
'myApp.controllers'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
$routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
index.html:
<!DOCTYPE html>
<html>
<head><title>Angular/Node exmaple</title></head>
<body>
<div id="main" ng-view></div>
</body>
</html>
Express Routes:
app.get('/', photos.index);
app.get('/photos', photos.findAll);
Access these routes in an Angular controller via $http or $resource service:
$http.get('http://api.domain.dev/photos').success(successCallback);
Additional Resources:
https://github.com/ithkuil/angular-on-server/wiki/Running-AngularJS-on-the-server-with-Node.js-and-jsdom
http://briantford.com/blog/angular-express.html
https://stackoverflow.com/a/10444923/243673

I had an existing angular project with a file structure like this (roughly):
/
app/
img/
scripts/
styles/
templates/
index.html
test/
I just created a new express app, and copied the contents of my app directory over to the /public directory in express, after removing all the existing content from /public
Then in the app.js file in express I did the following changes to the default config:
var express = require('express');
var routes = require('./routes');
// ** required my route module
var menu = require('./routes/menu');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
// ** I moved this above the app.router line below, so that static routes take precedence
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// ** removed the default index route
// app.get('/', routes.index);
// ** defined my route
app.get('/api/menu', menu.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Then obviously wrote my route file in express and changed the URL in the angular service to use the new api.
Also there was more work involved deciding where to put the specs and also merging the bower and node dependancies etc but that is probably too specific to my situation to include with this answer but happy to share if anyone might find it useful.

Related

How does express know this routing?

I create a simple express server and serve the static files
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(3000, () => {
console.log('Listening on port 3000')
})
When I head to localhost:3000, the index.html in my public directory renders for the route ' / '. I didn't explicitly write the route in my index.js file. How does express know this?
I've tried changing the file name from index.html to random.html and I get an error. CANNOT GET /
As mentioned in the comments, app.use(express.static('public')) is responsible for this. This will essentially serve all files in the public folder you have in the project. If you have an index.html in the public folder, then that will be served at the / endpoint automatically. This is a convention that most websites follow, and is documented in this SO post.
Here is the relevant documentation on express.static(...): https://expressjs.com/en/starter/static-files.html

Angular 2 'app-root' not loading on ExpressJS route

Im new to NodeJS and Express but i want a simple '/' route to Angular's default index.html (client/src/index.html) which contains the app-root tag.
The '/' route successfully serves the index.html file but it doesn't expand/load the 'app-root' tag into the component's html so i just get blank page.
Im not sure why it cant resolve the app-root tag when routed from Express. Only if i run Angular by 'ng serve' does the index.html successfully load the contents of the app-root tag.
My structure is as follows:
/client
/e2e
/node_modules
/app
app.component.css/html/ts
app.module.ts
/src
index.html
main.ts
package.json
server.js
server.js
var express = require('express');
var path = require('path');
var port = 80;
var app = express();
// set static folder
app.use(express.static(path.join(__dirname, '/client')));
app.get('/', function(req, res, next){
res.sendFile(__dirname + '/client/src/index.html');
});
app.listen(port, function(){
console.log("Server started on port " + port);
});
It look like you didn't do 'ng build' your angular app because main.ts is still there.
When you do the 'ng serve', angular compiles and serve it using webpack-dev-server.
If you want to serve your app from the your node as static, you need a compiled angular app.
You can do the following
$ cd client && ng build
There will be client/dist directory created where your compiled angular app is located and you can serve that on your express
You can change the directory in you server.js like below
app.use(express.static(path.join(__dirname, '/client/dist')));
res.sendFile(__dirname + '/client/dist/index.html');
Hope this helps

Find a css file node js

Hi I'm new to nodejs and I've just succeed to deploy a nodejs app online. Now I would like to know how to link CSS, JS or image files be cause when I try to do it like I used to, I get the error GET (not found).
The folder architecture is:
--public
--assets
--css
index.css
--js
--views
--index.ejs
--node modules
app.js
package.json
Assuming that I want to code the link index.css in index.ejs, what I need to write in my app.js file please.
app.js code:
var express = require('express');
var app = express.createServer();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.render('index');
});
app.listen(8080,'IP_ADRESS');
index.ejs code:
<link rel="stylesheet" type="text/css" href="/css/index.css">
The basic set up of serving static files in express :
var express = require("express");
var app = express();
...
app.use(express.static(__dirname + '/public'));
...
app.listen(3000);
Now in your .ejs in order to load the css styles or js scripts :
<link rel="stylesheet" href="/css/index.css"/>
First, there's a thing called a static file. Basically, that's a file that's sent over the internet without any kind of modification. Image and CSS files are typically static files.
It looks like you've put your static files in a folder called public.
Express has a built-in feature for sending static files, called express.static. You can use it like this:
// Require the modules we need.
var express = require('express');
var path = require('path');
// Create an Express app.
var app = express();
// Get the path to the `public` folder.
// __dirname is the folder that `app.js` is in.
var publicPath = path.resolve(__dirname, 'public');
// Serve this path with the Express static file middleware.
app.use(express.static(publicPath));
// ...
You should now be able to see static files. If your site is normally accessible at http://localhost:3000, you'll be able to see index.css at http://localhost:3000/css/index.css.
If you want to know way too much about express.static, you can check out a blog post I wrote that goes into Express's static files in depth.

serving a Single Page Angular App using Restify

I am new to AngularJs and wanted to start learning it. I was going to use Restify as my api/backend and was hoping it was possible to serve static files up for the route /.
app layout is something like this..
/nodesprinkler
node_modules/
public/
css/
main.css
bootstrap.css
js/
angular.js
app.js
...
img/
...
index.html
favicon.ico
server.js
routes.js
...
My server.js looks like so:
var restify = require('restify'),
app = module.exports = restify.createServer();
app.listen(8000, function() {
console.log('%s listening at %s', app.name, app.url);
});
/* Client Side Route */
app.get('/', restify.serveStatic({
directory: 'public',
default: 'index.html'
}));
module.exports.app = app;
routes = require('./routes');
How can i get Restify to serve up my static assets so it'll work like a regular express app works? I know restify is based off express, so there must be something simple that i'm missing. It will serve up / as index.html but any of my css and js files I dont have access to.
try express.static()
before app.listen put
app.use(express.static(__dirname+"/public"))
The docs
Try this:
app.get("/css|js|img/", restify.plugins.serveStatic({
directory: "./public"
}));
app.get(
"/.*/",
restify.plugins.serveStatic({
directory: "./public",
file: "index.html"
})
);
I'm creating my futur startup with the same technologies: Restify (that I rewrite) and Angular JS for the single app view.
I've tried of lots of solutions and the best one for me is :
Keep a WS with Restify (or what you want) WITHOUT any static files... I serve it with a dedicated server (python for dev, NGinx for production).
I know this is not the expected answer but give it a try.
python -m http.server on your angular directory is so simple :p

how to set path to the views (template) directory and to static files in node.js

I have created layout.jade, navigation.jade, and index.jade, and I want to glue them together.
In server.js, how do I
set the path to the views (template) directory, and
set the path to static files.
Is it required that node_module be placed in the folder that contains server.js?
Below is the code for server.js:
//create an app server
var express = require("express");
var server = express.createServer();
//set path to the views (template) directory
app.set('views', D:\#Programming\node.js\trial box\views);
//set path to static files
//how is the path to static files set?
app.use(express.static(__dirname + '/../public'));
//handle GET requests on /
app.get('/', function(req, res){
res.render('index.jade', {title: 'web project'});
});
//listen on localhost:3000
app.listen(3000);
Thank you in advance.
This questions a little old, but I'll still leave an answer. You'll need to place your app.use(... statement inside a callback function for app.configure() like so..
app.configure(function(){
app.use(express.static(__dirname + '/../public'));
});
You should use the express bin tool to bootstrap a project you'd get all that setup.
To install it:
sudo npm install express -g

Resources