I will explain the issue in as much detail as possible.
I am attempting to use AngularJS with Express and am running into trouble. I wish to display HTML files (not using a templating engine). These HTML files will have AngularJS directives.
However, I am not able to display a simple HTML file itself!
The directory structure is as follows:
Root
---->public
-------->js
------------>app.js
------------>controllers.js
---->views
-------->index.html
-------->partials
------------>test.html
---->app.js
The contents of public/js/app.js is:
angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {templateUrl: 'partials/test.html', controller: IndexCtrl});
$routeProvider.otherwise({redirectTo: '/'});
}]);
The contents of public/js/controllers/js is:
function IndexCtrl() {
}
The contents of the body tag in views/index.html is:
<div ng-view></div>
That's it. The expectation is that AngularJS will substitute the above view with test.html - views/partials/test.html whose contents are:
This is the test page!
enclosed within the paragraph tags. That's it!
Finally, the contents of ROOT/app.js file is:
var express = require('express');
var app = module.exports = express();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// routes
app.get('/', function(request, response) {
response.render('index.html');
});
// Start server
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
Now, when I do $node app.js in the root folder, the server starts without any error. However if I go to localhost:3000 in the browser, the URL changes to localhost:3000/#/ and the page gets stuck / freezes. I can't even check the console log in Chrome!
This is the problem that I am facing. Any clue about what I am doing wrong?
Finally figured it out - after many intense moments of hair pulling!!
The reason why the page freezes is because (explained step by step):
User launches localhost:3000
This requests the express server for '/'
Express renders index.html
AngularJS will render the template 'partials/test.html'.
Here, I am taking a wild guess - AngularJS has made a HTTP request for the page 'partials/test.html'.
However, you can see that express or rather app.js does not have a handler for this GET request. That is, the following code is missing:
app.get('partials/:name', function(request, response) {
var name = request.params.name;
response.render('partials/' + name);
});
inside app.js of the ROOT directory. Once I add this code, the page renders as expected.
Try following the design pattern in this working fiddle. Code shown below. You can replace the template option with templateUrl and it should still work fine.
var app = angular.module('app', []);
app.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/', {template: '<p>Index page</p>', controller: 'IndexCtrl'});
$routeProvider.otherwise({redirect:'/'});
}]);
app.controller('IndexCtrl', function(){
});
Related
I have a mean-stack application. By going to https://localhost:3000/#/home, it reads views/index.ejs. Here is the setting in app.js:
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
res.sendFile('index.ejs', { root: __dirname });
});
Actually, I don't use the feature of ejs in index.ejs. So now I want to use just a index.html rather than index.ejs.
I put the content of index.ejs in public/htmls/index.html and views/index.html. And here is the current setting in app.js:
var app = express();
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.all('/*', function(req, res, next) {
res.sendFile('index.html', { root: __dirname });
// res.sendFile('index.html'); // does not work either
});
However, running https://localhost:3000/#/home returns
Error: No default engine was specified and no extension was provided.
Does anyone know how to fix it?
Edit 1: by following the answer of user818510, I tried res.sendFile('index.html', { root: path.join(__dirname, 'views') }); in app.js, it still can NOT find index.html.
Whereas, in routes/index.js, the following can find index.html, but it gives a warning express deprecated res.sendfile: Use res.sendFile instead routes/index.js:460:9.
var express = require('express');
var router = express.Router();
var path = require('path');
... ...
router.get('*', function(req, res) {
res.sendfile('./views/index.html'); // works, but a deprecation warning
// res.sendFile('index.html', { root: path.join(__dirname, 'views') }); does not work
});
It is really confusing...
If it's a single page mean application, then you only need to start express with static and put index.html in static/ dir :
Project layout
static/
index.html
server.js
server.js
'use strict';
var express = require('express');
var app = express();
app.use(express.static('public'));
var server = app.listen(8888, function () {
console.log("Server started. Listening on port %s", server.address().port);
});
Now you can call http://localhost:8888/#home
It looks like a problem with the path. Your index.html is located at public/htmls/index.html and views/index.html. Your root option in res.sendFile should be __dirname+/public/htmls/ or __dirname+/views
In your code, you are using the path:
res.sendFile('index.html', { root: __dirname });
Your app.js would be in the project root where you have public directory alongside at the same level. Based on your rootoption in res.sendFile, you would have to place index.html at the same level as your app.js.
You should change the root path in res.sendFile. Use:
res.sendFile('index.html', { root: path.join(__dirname, 'public', 'htmls') });
OR
res.sendFile('index.html', { root: path.join(__dirname, 'views') });
The above root is based on the path that you've mentioned in your question.
Here's the link to the docs:
http://expressjs.com/en/api.html#res.sendFile
Your no default engine error is probably because you have commented the line where you set the view engine to ejs but still have existing ejs views. Uncommenting that line with the root path change should solve your issue.
Do not serve static content from an application server.
Use a web server for that, and in production, a content delivery network like Akamai.
A content delivery network will charge you per bandwidth (e.g: 10 cents per Terabyte). Serving the equivalent of 10 cents in Akamai can cost you thousands of dollars using cloud instances.
In addition to that, your servers will have unnecessary load.
If you absolutely have to serve static content from your application servers, then put a reverse proxy cache like nginx, varnish or squid in front of your server. But that will still be very cost inefficient. This is documented in the express website.
This is common practice in every Internet company.
I facing a problem that my Angularjs is not rendering or load in my Jade layout. Somehow the stylus is working perfectly with. I counldn't find out the reason why. I'm still the beginner in learing jade, stylus and angularjs
Below are my codes:
index.jade
!!! 5
html(ng-app='ng-app')
head
script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js')
script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.min.js')
script(src='https://cdn.firebase.com/v0/firebase.js')
script(src='http://firebase.github.io/angularFire/angularFire.js')
script(type='text/javascript', src='angular.js')
link(rel='stylesheet', href='style.css')
body
.addressBook(ng-controller='addressBook')
h1 Address Book
table(width='710px', border='0', cellspacing='0', cellpadding='0')
tr.title(height='35px', align='left')
td(width='130') Name
td(width='180') Email
td(width='210') Address
td(width='80') Mobile
tr.details(ng-repeat='contact in contacts')
td {{contact.name}}
td {{contact.email}}
td(style='padding-bottom: 30px;') {{contact.address}}
td {{contact.mobile}}
angular.js
function addressBook($scope)
{
$scope.contacts =
[
{name:'Peter', email:'john_peter#asd.co', address:'No.123, Road 12/20, Street Army, 58200 KL, Malaysia', mobile:'601231231234' },
{name:'Lim', email:'Amy#asd.co', address:'54, 13/15, Happy Garden, 58200 KL, Malaysia', mobile:'60123473534' }
];
}
app.js
var jade = require('jade')
, express = require('express')
, http = require('http')
, app = express();
var stylus = require('stylus');
require('./angular.js');
app.configure(function(){
console.log('Configuring views....');
app.set('port', 1234);
app.set('views', './');
app.use(express.bodyParser());
app.use(express.static( __dirname + '/'));
app.set('view engine', 'jade');
});
app.get('/test', function(req,res){
res.render('index.jade');
});
server = http.createServer(app);
server.listen(app.get('port'), function(){
}).on('error', function(err) {
throw err;
});
thank you in advanced for everyone who helps
I suspect the issue you are having is that the path to your views that you have specified is wrong and you are serving them up statically.
For example, if you have your views in a sub-directory of the base directory, and you have set the base directory to be served up as static content, it will serve up the jade as static content.
What you should do is put your views in a different folder to the static content so that is a sibling not a child and this should work. If you want to post your directory structure I can have a look.
As my username implies, I'm new to node.js. I'm trying to learn it. As part of this process, I'm working to setup a basic web site. This web site will show a couple of basic web pages and expose a single REST endpoint. The structure of my project is:
config.js
home.html
start.js
routes.js
server.js
resources
css
style.css
images
up.png
down.png
javascript
home.html.js
start.js has my main server code. That file gets executed via command line using 'node start.js'. Once started, my server begins listening on port 3000. The code in start.js looks like this:
var express = require('express');
var app = express();
var UserProfileHandler = require('./app/handlers/UserProfileHandler');
app.configure(function () {
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/');
app.use(express.logger({ stream: expressLogFile }));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
var routes = {
userProfiles: new UserProfileHandler()
};
function start() {
routeConfig.setup(app, routes);
var port = process.env.PORT || 3000;
app.listen(port);
console.log("SUCCESS: Server listening on port %d in %s mode", port, app.settings.env);
}
exports.start = start;
exports.app = app;
My routes.js file has the following:
function setup(app, routes) {
viewSetup(app);
apiSetup(app, routes);
}
function viewSetup(app) {
app.get('/', function (req, res) {
res.render("/home.html");
});
app.get('/home.html', function (req, res) {
res.render("/home.html");
});
}
function apiSetup(app, routes) {
app.get('/api/userProfiles/:username', routes.userProfiles.getUserProfiles);
}
I am trying to load home.html in a browser window. I attempt this by visiting http://localhost:3000 and http://localhost:3000/ and http://localhost:3000/home.html. Unfortunately, none of these work. In fact, I receive an error that says:
Express 500 Error: Failed to lookup view "/home.html"
I know that I'm close. If I visit http://localhost:3000/api/userProfiles/me I receive a JSON response back like I'm expecting. For some reason, i can't seem to return HTML though. My home.html file looks like the following.
<html>
<head>
<script type='text/javascript' src='/resources/javascript/home.html.js'></script>
</head>
<body>
We're up and running! <img src='/resources/images/up.png' />
</body>
</html>
Its a pretty basic HTML file. Even if the HTML comes back though, I'm concerned the JavaScript file and Image it references won't be accessible. I'm concerned of this because I'm not really sure how paths and such work in Node.
How do I get home.html to work in my Node setup?
Thank you!
as your view file is in same folder as your main file, below changes should make it work
1.change the view folder configuration line
from
app.set('views', __dirname + '/');//wont work
to
app.set('views', __dirname);//will work
2.change view render lines
from
res.render("/home.html");//wont work
to
res.render("home.html");//will work
with both the changes, the view should be working fine
update to below comments.
the issue you mentioned regarding the images,css and js is due to the static folder configuration which should be changed from
app.use(express.static(__dirname + '/public'));
to
app.use(express.static(__dirname + '/resources'));
as your static folder is named resources.
but make sure in your view you are refering the css/js/image files like
eg:
/css/style.css
/images/up.png
/images/down.png
/javascript/home.html.js
from your view file
Also if the above dint work, check if you have given the path correctly and also you can try by taking the
app.use(express.static(__dirname + '/resources'));
before the
app.use(express.methodOverride());
app.use(app.router);
lines like
app.configure(function () {
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/');
app.use(express.static(__dirname + '/public'));
//try changing the position of above line in app.configure and resatrt node app
app.use(express.logger({ stream: expressLogFile }));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
had similar problem in my case is
app.set('./views');
look for the dot, dont know why but the dot will mess it up.
I had it like this
app.set('/views') and no matter what i did couldt find the folder until added the dot.
I've set up my express site with poet recently. I can use post.url and all the locals which are provided to all views, except the url routing - for example, in my blog.jade view:
ul.blog-preview$
each post in postList$
li$
a(href=#{post.url}) #{post.title}$
The view renders fine, but the route express tries when clicking on the post.url: "http://localhost:8080/undefined/post/poet-testundefined" where the post I was trying to reach is called 'poet-test'. So, I tried printing out post.url within the view
p #{post.url}
and to my surprise it printed out fine as post/poet-test. So, obviously I tried browsing to localhost:8080/post/poet-test, but that didn't work either because of a reference error on post.title, which I suspect is a problem because the post is getting lost in routing somehow.
This is my site.js (or app.js as most are called) and I've included what I think must be relevant to solving this.
var express = require('express')
, app = module.exports = express()
, http = require('http')
, poet = require('poet')(app)
poet
.createPostRoute()
.createPageRoute()
.createTagRoute()
.createCategoryRoute()
.init(function(locals) {
locals.postList.forEach(function ( post ) {
console.log('loading post: ' + post.url)
})
})
app.configure(function(){
//...etc
app.use(app.router);
//...etc
app.use(express.static(__dirname + '/public'));
});
//Dev settings
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions:true, showStack:true }));
app.set('port', process.env.PORT || 8080);
app.use(express.logger('dev'));
});
//Production settings
//....etc
// controllers - load them
controllers = ["pages", "blog"]
for (i in controllers) {
controller = require('./controllers/' + controllers[i]);
controller.setup(app)
}
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
As you can see, I check the post.url for each post it loads in poet.init(function(post) { ... }) and each of those check out with the correct /post/title url... so, I'm a little stuck here. Perhaps logging routes somehow with app.router() or a poet specific solution.
Check out the examples in the Poet repo -- You shouldn't have to escape your hrefs.. looks like the urls in Poet are fine, just some wrestling with Jade, try this:
a(href=post.url) post.title
https://github.com/jsantell/poet/blob/master/examples/views/includes/postSnippet.jade#L3
I am building a Node Express application using Jade, and I am confused about how to route my views to the specific requests the browser will make. I understand that in order to get URLs to work in the browser, we need to use Node's routes; however, from looking online, I have discovered that Express has its own router.
I used PHPStorm to start up my project, and the index.jade will load... but how do I load the others? Here is my existing code:
var express = require('express'), routes = require('./routes'), http = require('http'), path = require('path');
var app = express();
app.configure(function ()
{
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('less-middleware')({ src:__dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function ()
{
app.use(express.errorHandler());
});
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function ()
{
console.log("Express server listening on port " + app.get('port'));
});
What is the most basic way to route my application, and where can I find more extensive documentation on this topic?
Thanks.
I understand that in order to get URLs to work in the browser,
we need to use Node's routes; however, from looking online,
I have discovered that Express has its own router.
Node.js per-se does not provide support for "routes", but Express does. You build your routes in Express using the following syntax:
app.[verb]('[url-path]', [handler]);
So your route app.get('/', routes.index) will process HTTP GET request to URL path / with the routes.index function. Express will automatically pass a request and response objects to your handler.
You can add more routes like this:
app.get('/users', routes.userList);
app.get('/user/:id', routes.userInfoView);
app.post('/user/:id', routes.userInfoSave);
You can find more information about this here http://expressjs.com/api.html#app.param
I am building a Node Express application using Jade, and I
am confused about how to route my views to the specific
requests the browser will make.
Once a route handler is invoked, say (routes.userList) you can call res.render() method inside userList to render the Jade file that you want. For example:
res.render('user_list',
{ users: [{name: "user1", age: 10}, {name: "user2", age: 20}] });
See here for more information: http://expressjs.com/api.html#res.render