My express (3.X) server looks like:
express = require "express"
app = express()
app.configure ->
app.use express.static(__dirname + '/public')
app.use app.router
console.log __dirname + '/public'
app.get "*", (req, res) ->
res.sendfile "index.html"
app.listen 1234
console.log "Server listening on port 1234"
I'm using it for an AngularJS project, so if anything is in the /public folder, I want it served directly. My /public folder has a scripts and templates folder in it.
However, when I go to http://localhost:1234/public/scripts/app.js, I get the contents of index.html
In this scenario, /public is your webroot. You need to change your reference to http://localhost:1234/scripts/app.js.
Related
I have deloyed a nodejs and angular app on heroku but after deployed routes are not working.
here is my webiste - https://murti123.herokuapp.com
with routes - enter link description here
but with routes it gives a can't get / errror.
i don't know how to resolve it
Here is My project Structureenter code here
You need to resolve your path to the frontend application
so assume that in /public folder you have the dist files from the builded frontend application
app.use(express.static(__dirname + "/public"));
and here you resolve that index.html for any route
app.get("*", function (req, res) {
//path is required at the top of the file ofcourse
//const path = require("path");
res.status(200).sendFile(path.resolve(__dirname + "/public/index.html"));
});
I have set up 2 static directories in express node as below.
app.use(express.static(__dirname + '/admin_public'));
app.use(express.static(__dirname + '/client_public'));
My doubt is whether I can connect the express server to angular 2 like below:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/admin_public/index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client_public/index.html'));
});
If the above 2 res.sendFile() are correct, when I build my hybrid app for angular.
1) How do I access my server (will it be something like: localhost:8080/client/public and localhost:8080/admin_public) for 2 different frontends, one for client and one for admin?
2) Is it the right way of connecting the express to 2 index.html's? If not, how should it be?
To create a virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function, specify a mount path for the static directory, as shown below:
app.use('/client', express.static(path.join(__dirname, 'client/public')));
app.use('/admin', express.static(path.join(__dirname, 'admin/public')));
Now, you can load the files that are in the public directory from the /client or /admin path prefix.
localhost:8000/client/
localhost:8000/admin/
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.
I have a directory like this
/Workspace
/app
app.js
/lib
/public
/styles
*.css
/scripts
*.js
/views
*.jade
from app.js in app, I have the following code:
libPath = __dirname + '/../lib'
... express stuff ...
app.configure(function() {
app.set('view', libPath + '/views')
... express stuff ...
app.use(express.static(libPath + '/public'))
... rest of the app ...
Now, the problem is that Jade can't find any of the views, but all the static assets are found. Thus, app.set('view') isn't working, but express.static is. If I copy the views directory to app, using __dirname + '/views' works fine. Anyone know why this is happening?
doing app.get('view'), I get a directory like this: /Users/jong/Workspace/app/../lib/views. I tried doing the absolute route /Users/jong/Workspace/lib/views as well to no avail. It's just weird that this directory works for static assets but not templates.
You have a mistype, the correct option name is views, not view.
Configure your application like
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { layout: true });
But the main root of issue is that you seem to misunderstand how express (and the MVC at all) works.
express sends out the static data to the browser, using your express.static configure directive, once the request url matches the existing static file path.
Otherwise, it tries to find any defined route for the requested path and to execute the associated controller (which may or may not use the template engine in turn).
So, in order to show e.g. the index page (even if it has no parameters), given you have an index.js in your views folder, you have to do something like
app.get('/', function (req, res, next) {
res.render('index', {});
});
I have a nodejs app and am using expressjs. I've defined my static directory, but when I access it, it doesn't load. My express config is:
var app = express.createServer().listen(8001);
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use('/public', express.static(__dirname + '/public'));
app.use(express.cookieParser());
app.use(express.session({ secret: "appsession" }));
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
});
Inside my /public directory I have 3 folders, css, js, and img. Inside css I have a style.css. When I try to access it directly via http://localhost:8001/public/css/style.css I get: Cannot GET /public/css/style.css
Any ideas what I could be doing wrong?
Thanks!
EDIT:
It seems to be related to how I have my routes setup. I'm doing it like this:
var routes = require('./routes')(db);
pp.get('/', routes.index);
Then in my index.js file, I have:
module.exports = function(db) {
return {
index: function(req, res, next) {
res.render('index');
}
}
}
I have my error handling enabled, but when I use the routing in this way, it doesn't use expresses error handling, however if I take this out, it does.
You setup the static http middleware as follows:
app.use(express.static(__dirname + '/public'));
And retrieve a file in ./public/css/style.css with the url:
"/css/style.css"
public is not part of the path when you actually request the file.
Change your static handler to this:
app.use('/public/css', express.static(__dirname + '/public/css'));
Then http://localhost:8001/public/css/style.css should get what you want
Full sample app that allows curl http://localhost:8001/public/css/style.css:
app.js
|-public
|-css
|-style.css
var express = require("express"),
app = express.createServer();
app.use('/public/css', express.static(__dirname + '/public/css'));
app.listen(8001);
Was running into the same issue found the answer here
https://github.com/senchalabs/connect/issues/298
When you have try to use nested files it kinda get lost,
it says fixed on the tracker a year ago, however i tried today and worked fine
I figured it out.
I have two services running on my host. Django is running the site at the root: http://myURL.com, and then Node is running at http://myURL.com/node
The configuration is fine with all the files in Node. The index.html file is requested fine, but the index.html when it requests the stylesheets and static files, the request gets caught by Django before it makes it to Node. Django saw the file and had no idea what it is and returned the 404 error.
By disabling Django from catching the requests to those files it all works fine.