I'd like to set up some subdomains for my Node.js app. I've built my site with express.js, and now I'd just like to throw up a little web tool on a subdomain of my site. I've tried using the vhost middleware with little luck, but am open to other approaches.
Any help would rock!
Ideally, I could just drop a new express app in a sub directory change a few lines of code, maybe change some DNS settings at it would work. The reason I'd like this is so that I can reuse a fresh instance of stylus and jade with new layouts and css styles and so forth.
Here's my normal app.js, the commented line is the attempt to use vhost.
var express = require('express'),
routes = require('./routes');
var app = module.exports = express.createServer();
// Configuration
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { layout: false });
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use('/courses', function (req, res, next) {
var privates = require('./.private.json'),
couch = require('nano')('https://' + privates.dbCreds.username + ':' + privates.dbCreds.password + '#wamoyo.iriscouch.com/');
});
app.use(require('stylus').middleware({
src: __dirname + '/public'
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
// VHOST - SUBDOMAIN
// app.use(express.vhost('adventures.innovationbound.com', require('./adventures/index').app));
app.use(function (req, res, next) {
res.status(404);
res.render('four', {
title: "Innovation Bound",
now: new Date().getFullYear()
});
});
app.use(function (err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/services', routes.services);
app.get('/events', routes.events);
app.get('/blog', routes.blog);
app.post('/contact', routes.contact);
// Courses
// app.get('/heartbeat', routes.heartbeat);
app.get('/courses', routes.courses);
// Tools
app.get('/point', routes.point);
app.listen(3000, function() {
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
This is using express 2.5, I wouldn't mind migrating over to 3 if need be.
Related
I am working on a single page web app with node/angular and jade. I am fairly new to angular, and I wanted to know what I have to do with my app.js file so that my first page template loads from my angular file rather than from my jade template.
I structured my files as such:
public/
index.html
javascript/
img/
stylesheets/
routes/
index.js
views/
partials/
a.jade
b.jade
app.js
This is what my app.js looks like:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
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());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser('cookies monster')); // Cookie secret
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
/*
* Views
*/
app.get('/', routes.index);
app.get('/a', routes.a);
app.get('/b', routes.b);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
My index.js looks like this:
exports.index = function(req, res){
res.render('index', { title: 'Test Application' });
};
// View A
exports.a = function(req, res) {
res.render('partials/a', { layout: false, test: 'LOL' });
};
// View B
exports.b = function(req, res) {
res.render('partials/b', { layout: false, test: 'YOLO' });
};
When I run this, It does not use the index.html as the first page. How would I go about doing so, so that the initial page template is actually the index.html? I can't seem to find the answer anywhere.
You could return the actual index.html file from your router.
app.get('/', function(req, res, next){
return res.sendfile(app.get('public') + '/index.html');
});
I should note that I also put app.set('public', path.join(__dirname, 'public')); inside app.js for easy access to the public directory.
Struck with routing issue in expressjs and AngularJs project.
It's not a single page application and I am not using any view engines such as jade.
We are just using plain HTML.
I am working on password reset functionality where user can reset the password by clicking a link provided by an email. So I assume there won't be any route change event in the context of Angular (Please correct me if I am wrong).
And my express configurations are as follows.
routes = require('./routes/index');
app.configure(function () {
app.use(express.static(__dirname + '/app'));
app.use('/css', express.static(__dirname + '/app/css'));
app.set('views', __dirname + '/app');
app.set("view options", { layout: false });
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');
app.use(express.favicon());
//app.use(require('connect').bodyParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
// Routes
app.get('/', routes.index);
app.get('/resetpassword.html/:resetcode', function (req, res) {
console.log("reset code: " + req.params.resetcode);
res.render('resetpassword.html/' + req.params.resetcode);
});
app.get('/api', function (req, res) {
res.send('Ecomm API is running');
});
// JSON API
app.post('/registeruser', usersApi.registerUser);
app.post('/api/login', usersApi.logIn);
app.post('/api/addgame', gamesApi.addGame);
app.get('*', routes.index);
// Start server
app.listen(2221, function () {
console.log("Express server listening on port %d in %s mode", 2221, app.settings.env);
});
and index.js
exports.index = function(req, res){
res.render('home.html');
}; // Always rending index.html which needs to be fixed.
And app.js from AnghularJs as follows
app.config(function ($routeProvider) {
$routeProvider
.when('/', { templateUrl: 'home.html' })
.when('/resetpassword.html/:resetcode', { templateUrl: '/resetpassword.html', controller: 'ResetPasswordCtrl' })
.otherwise({ redirectTo: '/' });
});
I am getting 500 internal error or view not found error.
Any suggestions please.
You are concatenating the password to the view name that you pass to render hence why Express does not find the view and returns a 500 error. You need to pass the data as an additional parameter to the render function as an object:
res.render('resetpassword.html', {resetcode: req.params.resetcode} );
Then in your view use resetcode directly e.g.
<span><%= resetcode %></span>
I'm having some problems trying to implement some middleware in my app.
Specicially, the app.use() does not seem to catch and I don't understand why.
Below is roughly what I have.
routes/index.js
var Sessions = require('../events');
module.exports = exports = function(app) {
app.use(Sessions.isLoggedIn);
//app.use() does not catch but this does
//app.all('*', Sessions.isLoggedIn);
// Home Page
app.get('/', displayHome);
app.get('/:library/:books', displayLibrary);
}
events.js
module.exports = exports = {
isLoggedIn: function(req, res, next) {
console.log('isLoggedIn');
return next();
}
Any suggestions as to why app.use() is not catching?
UPDATE:
Here is the configuration in ape.js
app.configure(function() {
app.set('port', process.env.VCAP_APP_PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.compress()); // compress responses
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(expressValidator);
app.use(express.cookieParser('locket'));
app.use(express.cookieSession({
key: 'locket',
secret: 'mySecret',
cookie: {httpOnly: true, expires: 0, path: '/'}
}));
// cache every file going out
app.use(function(req, res, next) {
if (!res.getHeader('Cache-Control')) {
res.setHeader('Cache-Control', 'public, max-age=' + (86400 / 1000));
}
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
});
routes(app);
The router is responding to the request before your middleware function has a chance to run.
app.js sets up several other middleware functions, then uses app.router. You then call your routes/index.js file, which uses a new middleware function which gets added after app.router.
use your isLoggedIn function before the router, or use it specifically with the routes that need to check login state:
app.get('/', Sessions.isLoggedIn, function(req, res) { ... });
As far as I can tell I'm configuring my global middleware function as described in the docs and in every forum post on the subject, but it is not being called. Does anyone see what I'm doing wrong? express 3.2.5. In the log output I see the following:
Express server listening on port 9000
inside route
GET / 200 7ms - 2b
I expect to see "inside middleware", then "inside route". Instead, I just see "inside route".
The code:
var express = require('express'), http=require('http'), path=require('path');
var app = express();
app.enable('trust proxy');
app.set('port', process.env.PORT || 9000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('layout', 'layout');
app.use(require('express-ejs-layouts'));
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride())
app.use(express.cookieParser('kfiwknks'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
} else {
app.use(function(err, req, res, next){
console.error (error);
res.send (500, "Internal server error");
});
}
app.use (function (req, res, next) {
console.log ("inside middleware");
next();
});
app.get ("/", function (req, res) {
console.log ("inside route");
res.send(200);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
This related post:
Express 3 error middleware not being called
is specific to error handling middleware. Mine is a vanilla middleware.
You should put your middleware before you use app.router.
...
app.use (function (req, res, next) {
console.log ("inside middleware");
next();
});
...
app.use(app.router);
Updated answer for Express 4 users from the Express 4 docs. See example from docs below. Note that app.router is deprecated and no longer used. I also added a dummy route to make the ordering clear.
You define error-handling middleware last, after other app.use() and routes calls
Example:
var bodyParser = require('body-parser');
app.use(bodyParser());
app.get('/', function(req, res) {
res.send('hello world');
})
app.use(function(err, req, res, next) {
// logic
});
I've been playing around with Node.js/Express and following the tutorial here and when I try to launch the app.js it takes 4 minutes for it to timeout while sending the style.css. I'm using Chrome to monitor the network traffic. Am I missing something in setting up the stylus?
This is my app.js:
var express = require('express');
var ArticleProvider = require('./articleprovider-memory').ArticleProvider;
var app = module.exports = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(require('stylus').middleware({debug: true, src: "#{__dirname}/../public", dest: "#{__dirname}/../public"}));
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());
});
var articleProvider= new ArticleProvider();
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', { locals: {
title: 'Blog',
articles:docs
}
});
});
});
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
EDIT:
I found the problem.
var app = module.exports = express.createServer();
I removed the module.exports and it seems to be working.
EDIT:
If you have this problem with Nodejs simply re-install it.