ui-router (0.2.18) with dot parameter - javascript

I'm developing angular app (1.5.2) and in one case have URL for state function as follows
http://localhost:3000/payment/1.1/2/3
But I'm getting an error:
Cannot GET /payment/1.1/2/3
Version of ui-router - 0.2.18. I read that they fixed that issue but for me it doesn't work. Same answers on SO doesn't help me too.
State config for this:
.state('payment', {
url: '/payment/:token/:id/:chanel_id',
templateUrl: 'app/payment/payment.html',
controller: 'PaymentController',
controllerAs: 'vm'
});
My server.js file:
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
var historyApiFallback = require('connect-history-api-fallback');
function browserSyncInit(baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
var server = {
baseDir: baseDir,
routes: routes,
middleware: [ historyApiFallback() ]
};
browserSync.instance = browserSync.init({
startPath: '/',
server: server,
browser: browser
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});
gulp.task('serve:dist', ['build'], function () {
browserSyncInit(conf.paths.dist);
});
gulp.task('serve:e2e', ['inject'], function () {
browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});
gulp.task('serve:e2e-dist', ['build'], function () {
browserSyncInit(conf.paths.dist, []);
});

What is your webserver.
You must redirect all request on your index.html if the request is not a file.
I think you must add this in your router $locationProvider.html5Mode(true);
Solution for BrowserSync and Gulp.
First install connect-history-api-fallback:
npm install connect-history-api-fallback --save-dev
Then edit your gulp/server.js and add the middleware:
var historyApiFallback = require('connect-history-api-fallback');
var server = {
baseDir: baseDir,
routes: routes,
middleware: [ historyApiFallback() ]
};

Related

express.js router unit testing error

I have a node/express application with a controller and service. While running the unit test for controller via Grunt/Jasmine, the test runs fine but after the coverage summary I get the following error:
error: Error on SAVE state TypeError: Cannot read property 'apply' of undefined
at /node_modules/express/lib/router/index.js:603:14
at next (/node_modules/express/lib/router/index.js:246:14)
at next (/node_modules/express/lib/router/route.js:100:14)
Controller.js
var express = require('express'),
router = express.Router();
module.exports = function(app) {
app.use('/api', router);
router.post('/save', function(req, res, next) {
// Service code is invoked here with the success/error callback
// on success - res.json(response);
// on error - res.status(err.status);
});
}
ControllerSpec.js
var app = require('../mockApp'); // the app.js and the express app is mocked here
var httpMocks = require('node-mocks-http');
var request = require('request');
describe("Controller SAVE Action", function () {
it("With Error", function () {
spyOn(service, "save").andCallFake(function (req, res, headers, callback) {
callback({category: "Error"});
});
var rout = app.getRouter("/state"); // the mocked app.js contains a getRouter function which returns the corresponding router which is simply express.Router()
var request = httpMocks.createRequest({
method: 'POST',
url: '/save',
headers: {"authorization": "success"}
});
var response = httpMocks.createResponse();
rout(request, response);
var data = JSON.parse(response._getData());
expect(data.code).toEqual(400);
});
});
Mocked app.js
var m = {};
var routers = {};
module.exports = {
get: function (name) {
return m[name];
}, set: function (name, obj) {
m[name] = obj;
}, use: function (path, router) {
if (router) {
routers[path] = router;
}
}, getRouter: function (path) {
return routers[path];
}
};
Mocked Express.js
var app = require('./app'); // Mocked app.js
var services = {};
var serviceFiles = glob.sync(rootPath + '/app/services/*.js');
serviceFiles.forEach(function (file) {
var service = require(file)(app);
services[service.serviceName] = service;
});
app.set("services", services);
var controllers = glob.sync(rootPath + '/app/controllers/*.js');
controllers.forEach(function (controller) {
require(controller)(app);
});

Node hapi app starts, but doesnt appear to bind to port

I have an hapi app that is in development. Upon running my usual node-foreman with Procfile, the app loads in the command line with no errors, but upon browsing to the configured port, the page errors, no connection, or specifically, connection refused. Back to the CLI, no errors. simple message from the server.start "Server running on http://localhost:3000"
I tried directly launching with gulp (no errors). No browser access.
I tried directly launching with node (no errors). No browser access.
I tried creating a hello world app with hapi, and express, both had no errors and DID load in the browser.
I even version controlled the code back to a version I know worked. Starts server fine from CLI, but no browser loading/access.
I'm a little stuck, would love any thoughts on even a path to go down to trouble shoot.
Thank you in advance.
Here is the app JS:
var config = require('./config');
hapi = require('../lib/hapi'),
chalk = require('chalk'),
module.exports.init = function (callback) {
//init app bserver
server = hapi.init();
callback(server, config );
};
module.exports.start = function (callback) {
var _this = this;
_this.init(function (server, config) {
// Start the app by listening on <port>
server.start(function () {
// Logging initialization
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| ' + config.app.title+ '\t\t\t|'));
console.log('+-----------------------------------------------------------+');
console.log(chalk.green('| Environment:\t' + process.env.NODE_ENV));
console.log(chalk.green('| Standard Port:\t' + config.port));
if (config.https.ssl === true ) {
console.log(chalk.green('| Secure Port:\t' + config.https.port));
console.log(chalk.green('| HTTPs:\t\ton'));
}
console.log(chalk.green('| App version:\t' + config.version));
console.log(chalk.green('| App url:\t\t' + ((config.https.ssl === true ? 'https' : 'http')+"://"+config.url)));
console.log('+-----------------------------------------------------------+');
console.log('| Database Configuration\t\t\t\t\t|');
console.log('+-----------------------------------------------------------+');
console.log(chalk.green(JSON.stringify(config.db, null, 4)));
console.log('+-----------------------------------------------------------+');
if (callback) callback(server, db, config);
});
return server;
});
};
AND HERE IS THE HAPI INCLUDE:
var config = require('../general/config'),
Hapi = require('hapi'),
Good = require('good'),
Hoek = require('hoek'),
Inert = require('inert'),
Vision = require('vision'),
Path = require('path'),
Boom = require('boom'),
Bell = require('bell'),
Cookie = require('hapi-auth-cookie'),
Url = require('url'),
hapiAuthSessions = require('./sessions'),
Promise = require('bluebird'),
fs = require('fs');
/* Initialize ORM and all models */
module.exports.initDBConnections = function( server ) {
server.register([
{
register: require('hapi-sequelize'),
options: [
{
sequelize: new Sequelize(process.env.DATABASE_URL),
name: config.db.connection.database,
models: config.files.server.models,
sync: true,
forceSync:false
}
]
}
], function(err) {
Hoek.assert(!err, err);
});
}
/**
* Initialize rendering engine
*/
module.exports.initRenderingEngine = function (server) {
var paths = [];
var layouts = [];
var partials = [];
var helpers = [];
/* add each module paths to rendering search, assume if route, there is a view fr module */
config.files.server.routes.forEach(function (routePath) {
var rp = Path.relative(Path.join(__dirname,'../../'),Path.resolve(Path.dirname(routePath)+'/../../'))
if(fs.existsSync(rp+'/server/views/'+config.theme+'/content'))
paths.push(rp+'/server/views/'+config.theme+'/content');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/errors'))
paths.push(rp+'/server/views/'+config.theme+'/errors');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/layouts'))
layouts.push(rp+'/server/views/'+config.theme+'/layouts');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/partials'))
partials.push(rp+'/server/views/'+config.theme+'/partials');
if(fs.existsSync(rp+'/server/views/'+config.theme+'/helpers'))
helpers.push(rp+'/server/views/'+config.theme+'/helpers');
});
server.views({
engines: {
html: require('handlebars')
},
path: paths,
layoutPath: layouts,
partialsPath: partials,
helpersPath: helpers,
layout: 'base.view'
});
}
/**
* Initialize local variables
*/
module.exports.initLocalVariables = function (server) {
// Setting application local variables
for (var property in config) {
if (config.hasOwnProperty(property)) {
if (!server.app[property]) {
server.app[property] = config.app[property]
}
}
}
};
/**
* Initialize static routes for browser assets
*/
module.exports.initStaticRoutes = function (server) {
server.route([{
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../public'),
redirectToSlash: true,
listing: false,
defaultExtension: 'html'
}
}
},{
method: 'GET',
path: '/assets/vendor/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../node_modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'js'
}
}
}]);
}
/**
* Initialize server logging
*/
module.exports.initLogging = function (server) {
return {
ops: {
interval: 1000
},
reporters: {
myConsoleReporter: [{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ log: '*', response: '*' }]
}, {
module: 'good-console'
}, 'stdout']
}
};
}
/**
* Initialize App Tenant
*/
module.exports.initAppTenant = function (server) {
server.ext('onRequest', function (req, res) {
server.app['tenant'] = req.info.hostname;
res.continue();
});
};
/**
* Initialize ensure SSL
*/
module.exports.initSSL = function(server) {
server.select('http').route({
method: '*',
path: '/{p*}',
handler: function (req, res) {
// redirect all http traffic to https
console.log('redirecting',config.url + req.url.path);
return res.redirect('https://' + config.url + req.url.path).code(301);
},
config: {
description: 'Http catch route. Will redirect every http call to https'
}
});
}
/**
* Initialize static routes for modules in development mode browser assets
*/
module.exports.initModulesStaticRoutes = function(server) {
if (process.env.NODE_ENV === 'development') {
server.route({
method: 'GET',
path: '/modules/{param*}',
handler: {
directory: {
path: Path.join(__dirname, '../../modules'),
redirectToSlash: false,
listing: false,
defaultExtension: 'html'
}
}
});
}
}
/**
* Configure the modules server routes
*/
module.exports.initModulesServerConfigs = function (server) {
config.files.server.configs.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};
/**
* Configure the modules server routes
*/
module.exports.initModulesServerRoutes = function (server) {
config.files.server.routes.forEach(function (routePath) {
require(Path.resolve(routePath))(server);
});
};
/**
* Configure Socket.io
*/
module.exports.configureSocketIO = function (server) {
// Load the Socket.io configuration
var server = require('./socket.io')(server);
// Return server object
return server;
};
/**
* Initialize hapi
*/
module.exports.init = function init() {
var server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
},
state: {
isSameSite: 'Lax'
}
},
debug: {
'request': ['error', 'uncaught','all','request']
},
cache: [
{
name: 'cacheMem',
engine: require('catbox-memcached'),
host: '127.0.0.1',
port: '8000',
partition: 'cache'
},{
name : 'cacheDisk',
engine : require('catbox-disk'),
cachePath: '/var/tmp',
partition : 'cache'
}
]
});
server.connection({
labels: 'http',
port: config.port
});
if(config.https.ssl == true) {
server.connection({
labels: 'https',
port: config.https.port,
tls: {
key: config.https.key,
cert: config.https.cert
}
});
/* redirect ssl */
this.initSSL(server);
}
server.register([Vision,{register: Good, options: this.initLogging(server)},Cookie,Bell,Inert], function(err) {
Hoek.assert(!err, err);
var _this = module.exports;
var _thisServer = server.select((config.https.ssl == true ? 'https' : 'http'));
/* Initialize sessions */
hapiAuthSessions._init(_thisServer);
/* detect app tenant */
_this.initAppTenant(_thisServer);
/* app local variables */
_this.initLocalVariables(_thisServer);
/* logging */
_this.initLogging(_thisServer);
/* static file serving */
_this.initStaticRoutes(_thisServer);
/* module config, routes, static routes */
_this.initModulesStaticRoutes(_thisServer);
_this.initModulesServerConfigs(_thisServer);
_this.initModulesServerRoutes(_thisServer);
/* rendering engine */
_this.initRenderingEngine(_thisServer);
// Configure Socket.io
server = _this.configureSocketIO(_thisServer);
//server.start located in ../general/app.js
});
return server;
}
HERE IS THE CLI OUTPUT:
[13:58:31] [nodemon] starting `node --inspect server.js`
[13:58:31] [nodemon] child pid: 5596
Debugger listening on ws://127.0.0.1:9229/e2f5837f-b552-4156-b004-e7adb3d30d05
For help see https://nodejs.org/en/docs/inspector
+-----------------------------------------------------------+
| APP - Development Environment |
+-----------------------------------------------------------+
| Environment: development
| Standard Port: 3000
| Secure Port: 3001
| HTTPs: on
| App version: 0.3.0
| App url: https://localhost:3001
+-----------------------------------------------------------+
| Database Configuration |
+-----------------------------------------------------------+
{
"client": "postgresql",
"connection": {
"host": "localhost",
"port": "5432",
"database": "database",
"user": "user",
"password": "password",
"ssl": true
},
"pool": {
"min": 2,
"max": 10
},
"migrations": {
"tableName": "knex_migrations"
},
"debug": true
}
+-----------------------------------------------------------+
Ok. I found the answer (this is twice in a week over looking small detail -- Shame on me).
The smaller problem, that lead me to the larger problem, was upon server.start(callback) I didn't have any error checking, similar to:
server.start(function(err) {
if(err) {
throw err;
}
});
Once I added the err logging, it exposed the reason the server was quietly failing.
My Hapi config was requiring a memcached module, and I had not started my memcached server locally.
All back to to working as designed :)

Ui-router refresh issue

I have configured my ui-router like this:
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: "/home",
templateUrl : 'home/home.html',
controllerUrl: 'home/controller.js'
})
.state('blog', {
url: "/blog",
templateUrl : 'blogger/blog.html',
controllerUrl: 'bloger/controller.js'
})
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
});
Server code :
var express = require('express');
var serveStatic = require('serve-static');
var server_port = 9000;
var server_ip_address = '127.0.0.1'
var app = express();
app.use(express.static('app'));
app.use(serveStatic('app', {'index': ['index.html', 'index.htm']}));
dirName = 'app';
options = {
root: dirName,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
app.get('*', function(req, res) {
return res.sendFile('index.html', options);
});
app.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + server_port)
});
But whenever I hit Ctrl/Command + R (or refresh), it says that it cannot find the path? How can I get around this problem?
Folder structure : Views : ./app/home/, app/blog/ Basefile:
./app/index.html Angular UI-routing from : ./app/base.js
The problem would be in the server settings. Angular is Front Controller application. You need every request redirect to index.html/index.php on your server. Htaccess settings in apache for example. Further information can be found here: htaccess redirect for Angular routes
The Problem is from your server side you should handle all routes in your server.js file.
For Example here is the snippet
router = settings.express.Router()
dirName = settings.path.resolve(__dirname, '..', '..');
options = {
root: dirName + '/website/views',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
router.get('*', function(req, res) {
return res.sendFile('index.html', options);
});
You can Use the below code in your app.js, & then it work :
UPDATED :
/** Below code set the html as your default engine*/
var fs = require('fs');
app.engine('html',function(path,opt,fn){ //manishp
fs.readFile(path,'utf-8',function(err,str){
if(err) return str;
return fn(null,str);
});
});
app.get('*',function(req,res){
res.render('<your_layout_file_or_basefile>');
});
This is mainly because your AngularJS routes aren't actual html pages. An example would be if you have a route in your angular app to /login. This url works fine if you link to it from inside your app but if a user tries to go directly to that page the server will return a 404.
This is because AngularJS HTML5 mode uses the History API to push a new url to your browser. Yes, this require some extra work on the server side to have those url return the correct content.

Backbone route with push state not working on page refresh

var Backbone = require('backbone'),
SellerProfileView = require('./views/seller/SellerProfileView');
var Router = Backbone.Router.extend({
routes: {
":user_name" : "sellerProfile"
},
sellerProfile: function (username) {
"use strict";
var sellerProfile = new SellerProfileView({username: username});
}
});
module.exports = Router
var Router = require('./router'),
Backbone = require('backbone'),
$ = require('jquery');
var app = {
init: function () {
"use strict";
Backbone.$ = $;
this.router = new Router();
$(document).ready(function () {
Backbone.history.start({ pushState: true, route: '/' });
});
}
};
module.exports = app;
app.init();
I get the below error if i refresh the page without the hash
Error response
Error code 404.
Message: File not found.
Error code explanation: 404 = Nothing matches the given URI.
Please help.
pushState will try to load the ressource.And it seems your server is not loading anything at 'yourwebsiteurl.com/'

gulpfile browsersync nodemon too much ram

My gulpfile is not functioning how I'd like. When I run the default task gulp my browser is launched but hangs at waiting for localhost... in the lower left corner. If I refresh then the server works as expected. I'd also like to edit my code and get the updates showing in my browser. This feature works but gulp grows to ~300mb of ram after developing for a while.
'use strict';
process.env.DEBUG = process.env.DEBUG || 'r3dm:*';
var gulp = require('gulp'),
// ## Style
concat = require('gulp-concat'),
stylus = require('gulp-stylus'),
swiss = require('kouto-swiss'),
mincss = require('gulp-minify-css'),
// ## Bundle
browserify = require('browserify'),
watchify = require('watchify'),
envify = require('envify/custom')({ NODE_ENV: 'development' }),
uglifyify = require('uglifyify'),
bundleName = require('vinyl-source-stream'),
//brfs = require('brfs'),
// ## utils
plumber = require('gulp-plumber'),
util = require('gulp-util'),
noopPipe = util.noop,
//logPipe = util.log,
watch = require('gulp-watch'),
yargs = require('yargs').argv,
debug = require('debug')('r3dm:gulp'),
// ## min
imagemin = require('gulp-imagemin'),
//pngcrush = require('imagemin-pngcrush'),
// ## Serve/Proxy/Reload
nodemon = require('gulp-nodemon'),
sync = require('browser-sync'),
reload = sync.reload,
// ## React
react = require('gulp-react'),
// ## production?
production = yargs.p;
var paths = {
main: './client.js',
jsx: './components/**/**.jsx',
stylusMain: './components/app.styl',
stylusAll: './components/**/*.styl',
css: './public/css/',
server: './server.js',
serverIgnore: [
'gulpfile.js',
'public/',
'components/**/*.styl',
'bower_components/',
'node_modules/'
],
publicJs: './public/js'
};
var watching = false;
var reloadDelay = 6500;
if (production) {
// ## Set with `-p`
console.log('\n', 'Production mode set', '\n');
}
gulp.task('stylus', function() {
return gulp.src(paths.stylusMain)
.pipe(plumber())
.pipe(stylus({
use: [
swiss()
],
'include css': true
}))
.pipe(concat('main.css'))
.pipe(production ? mincss() : noopPipe())
.pipe(gulp.dest(paths.css));
});
gulp.task('jsx', function() {
return gulp.src('./components/**/*.jsx')
.pipe(react())
.pipe(gulp.dest('./components'));
});
gulp.task('jsx-watch', function() {
return gulp.src(paths.jsx)
.pipe(watch(paths.jsx))
.pipe(react({
harmony: true
}))
.pipe(gulp.dest('./components'));
});
gulp.task('bundle', function(cb) {
browserifyCommon(cb);
});
gulp.task('sync', ['bundle', 'stylus', 'server'], function() {
sync.init(null, {
proxy: 'http://localhost:9000',
logLeval: 'debug',
files: [
'public/**/*.*',
'!public/js/bundle.js'
],
port: 9002,
open: true,
reloadDelay: reloadDelay
});
});
gulp.task('server', function(cb) {
var called = false;
nodemon({
script: paths.server,
ext: '.js',
ignore: paths.serverIgnore,
env: {
'NODE_ENV': 'development',
'DEBUG': 'r3dm:*'
}
})
.on('start', function() {
if (!called) {
called = true;
setTimeout(function() {
cb();
}, reloadDelay);
}
})
.on('restart', function(files) {
if (files) {
debug('Files that changed: ', files);
}
setTimeout(function() {
debug('Restarting browsers');
reload();
}, reloadDelay);
});
});
gulp.task('watch', function() {
gulp.watch(paths.stylusAll, ['stylus']);
});
gulp.task('setWatch', function() {
watching = true;
});
gulp.task('image', function() {
gulp.src('images/**/*')
.pipe(imagemin({
progressive: true,
optimizationLevel: 2
}))
.pipe(gulp.dest('public/images'));
});
gulp.task('default', [
'setWatch',
'jsx-watch',
'bundle',
'stylus',
'server',
'sync',
'watch'
]);
function browserifyCommon(cb) {
cb = cb || noop;
var config;
if (watching) {
config = {
basedir: __dirname,
debug: true,
cache: {},
packageCache: {}
};
} else {
config = {
basedir: __dirname
};
}
var b = browserify(config);
b.transform(envify);
//b.transform(brfs);
if (!production) {
debug('Watching');
b = watchify(b);
b.on('update', function() {
bundleItUp(b);
});
}
if (production) {
debug('Uglifying bundle');
b.transform({ global: true }, uglifyify);
}
b.add(paths.main);
bundleItUp(b);
cb();
}
function bundleItUp(b) {
debug('Bundling');
return b.bundle()
.pipe(plumber())
.pipe(bundleName('bundle.js'))
.pipe(gulp.dest(paths.publicJs));
}
function noop() { }
update: It may not be my gulpfile. I waited patiently and it eventually loads my app's root page. Here's my server.js file
'use strict';
require('dotenv').load();
require('newrelic');
var express = require('express'),
app = express(),
keystone = require('keystone'),
mongoose = require('mongoose'),
// ## Util
debug = require('debug')('r3dm:server'),
utils = require('./utils/utils'),
// ## React
React = require('react'),
Router = require('./components/Router'),
state = require('express-state'),
// ## Flux
Fetcher = require('fetchr'),
mandrillServ = require('./services/mandrill'),
blogServ = require('./services/blog'),
ContextStore = require('./components/common/Context.store'),
RouterStateAction = require('./components/common/RouterState.action'),
// ## Express/Serve
morgan = require('morgan'),
serve = require('serve-static'),
favicon = require('serve-favicon'),
body = require('body-parser'),
multer = require('multer'),
compress = require('compression'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
flash = require('connect-flash'),
helmet = require('helmet');
// ## State becomes a variable available to all rendered views
state.extend(app);
app.set('state namespace', 'R3DM');
app.set('port', process.env.PORT || 9000);
app.set('view engine', 'jade');
app.use(helmet());
app.use(morgan('dev'));
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(cookieParser('12345'));
app.use(body.urlencoded({ extended: false }));
app.use(body.json());
app.use(multer());
app.use(compress());
app.use(flash());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
// ## Fetcher middleware
Fetcher.registerFetcher(mandrillServ);
Fetcher.registerFetcher(blogServ);
app.use('/api', Fetcher.middleware());
keystone.app = app;
keystone.mongoose = mongoose;
keystone.init({
'cookie secret': '12345',
'auth': true,
'user model': 'User',
'mongo': process.env.MONGO_URI,
'session': true
});
keystone.import('models');
keystone.static(app);
keystone.routes(app);
keystone.mongoose.connect(keystone.get('mongo'));
app.use(serve('./public'));
app.get('/500', function(req, res) {
res.render('500');
});
app.get('/emails/:name', function(req, res) {
var locals = {},
name = req.params.name,
nameArr;
nameArr = name
.split(' ')
.map(function(_name) {
_name = _name.replace(/[^A-Za-z_'-]/gi, '');
_name = utils.capitalize(_name);
return _name;
});
locals.name = nameArr[0];
res.render('email/greet', locals);
});
app.get('/*', function(req, res, next) {
debug('req', req.path);
debug('decode req', decodeURI(req.path));
Router(decodeURI(req.path))
.run(function(Handler, state) {
Handler = React.createFactory(Handler);
debug('Route found, %s ', state.path);
var ctx = {
req: req,
res: res,
next: next,
Handler: Handler,
state: state
};
debug('Sending route action');
RouterStateAction(ctx);
});
});
// Use a hot observable stream for requests
var hotObservable = ContextStore.publish();
// Run on next sequence
hotObservable.subscribe(function(ctx) {
if (!ctx.Handler) { return debug('no handler'); }
debug('rendering react to string', ctx.state.path);
var html = React.renderToString(ctx.Handler());
debug('rendering jade');
ctx.res.render('layout', { html: html }, function(err, markup) {
if (err) { return ctx.next(err); }
debug('Sending %s', ctx.state.path);
return ctx.res.send(markup);
});
});
// Start listening listening to observable sequence;
hotObservable.connect();
app.use(function(req, res) {
res.status(404);
res.render(404);
});
app.use(function(err, req, res, next) { //jshint ignore:line
debug('Err: ', err);
res
.status(500)
.send('Something went wrong');
});
// keystone.start();
app.listen(app.get('port'), function() {
debug('The R3DM is go at: ' + app.get('port'));
debug(new Date());
});
line debug('req', req.path); is eventually reached after ~120 seconds. But if I refresh when the tab is first opened it loads immediately.
update 2: I was able to fix the initial loading issue by increading the dealy to 6500ms. Now I need to find what's causing the memory leak.

Categories

Resources