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 :)
Related
The following code is client and server side code to use webRTC connection. It's working perfectly in localhost. when i deployed to linux shared hosting server., it's getting error.
This is my server side code.
var http = require('http');
var express = require('express');
var ExpressPeerServer = require('peer').ExpressPeerServer;
var app = express();
var server = http.createServer(app);
var options = {
debug: true,
key: 'peerjs',
allow_discovery: true,
ssl: {
key: '',
cert: ''
},
proxied: true
};
var expressPeerServer = ExpressPeerServer(server, options);
app.use('/api', expressPeerServer);
app.use('/', express.static('.'));
app.use('/list', function (req, res) {
return res.json(Object.keys(expressPeerServer._clients.peerjs));
});
var port = process.env.PORT || 8080;
server.listen(port, function () {
console.log('Basic-ss live at', port);
});
expressPeerServer.on('connection', function (id) {
console.log('Peer connected with id:', id);
});
expressPeerServer.on('disconnect', function (id) {
console.log('Peer %s disconnected', id);
});
the following is the client side code for connect peer.
initPeer(peerId) {
this.peer = new Peer(peerId, {
host: 'localhost',
port: 8080,
path: '/api',
key: 'peerjs',
debug: 3,
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
}
});
setTimeout(() => {
this.currentPeerId = this.peer.id;
if (this.currentPeerId !== null) {
isPeerConnected = true;
} else {
isPeerConnected = false;
}
console.log('Current Peer ID', this.currentPeerId);
}, 4000);
}
this code is working perfectly in localhost.
this is the code i am uploading in server.
this.peer = new Peer(peerId, {
host: '', ===> my domain name here.
port: 8080,
path: '/api',
key: 'mebstelemedclinic',
debug: 3,
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
{
url: 'turn:192.158.29.39:3478?transport=udp',
credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
username: '28224511:1379330808'
}
]
}
});
if use the same server code and the above client side code., it's getting connection error.
WebSocket connection to 'wss://mydomain.in:8080/api/peerjs?key=peerjs&id=LY42201PH-yKy04f-ygqZJhqrBmezG6&token=n42tatqqn9e' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
i was struck at this point from long time. Help me how can i overcome this error. thank you.
You should add the code below to your path nano site_name in /etc/nginx/sites-available:
location {
proxy_pass Ip address; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; }
I was trying to make a Polyfill.io server as a microservice on AWS Lambda, it was supposed to run a JavaScript file on a GET request.
When I run the service locally the call goes through but it returns an undefined object instead of JS file.
I'm running it locally using serverless, my code is based on polyfill.io's github repo
I've modified the service/index.js to be like so:
'use strict';
const express = require('express');
const path = require('path');
const Raven = require('raven');
const morgan = require('morgan');
const shrinkRay = require('./shrink-ray');
const app = express().enable("strict routing");
const one_day = 60 * 60 * 24;
const one_week = one_day * 7;
const one_year = one_day * 365;
app.use(shrinkRay({
brotli: {quality: 11}
}));
let ravenClient;
// Log requests
if (process.env.ENABLE_ACCESS_LOG) {
app.use(morgan('method=:method path=":url" request_id=:req[X-Request-ID] status=:status service=:response-time bytes=:res[content-length]'));
}
process.on('uncaughtException', (err) => {
console.log('Caught exception', err);
});
// Set up Sentry (getsentry.com) to collect JS errors.
if (process.env.SENTRY_DSN) {
const about = require(path.join(__dirname, '../about.json'));
ravenClient = new Raven.Client(process.env.SENTRY_DSN, {
release: about.appVersion || process.env.SENTRY_RELEASE || 'unknown'
});
ravenClient.patchGlobal();
app.use(Raven.middleware.express.requestHandler(ravenClient));
}
// Do not send the X-Powered-By header.
app.disable("x-powered-by");
// Default response headers
app.use((req, res, next) => {
// Ensure our site is only served over TLS and reduce the chances of someone performing a MITM attack.
res.set('Strict-Transport-Security', `max-age=${one_year}; includeSubdomains; preload`);
// Enables the cross-site scripting filter built into most modern web browsers.
res.set('X-XSS-Protection', `1; mode=block`);
// Prevents MIME-sniffing a response away from the declared content type.
res.set('X-Content-Type-Options', `nosniff`);
// Sets content-type
res.set('Content-Type', `application/javascript`);
// Prevents clickjacking by prohibiting our site from being included on other domains in an iframe.
res.set('X-Frame-Options', `sameorigin`);
res.set('Cache-Control', 'public, s-maxage=' + one_year + ', max-age=' + one_week + ', stale-while-revalidate=' + one_week + ', stale-if-error=' + one_week);
res.set('Surrogate-Key', process.env.SURROGATE_KEY || 'polyfill-service');
res.set('Timing-Allow-Origin', '*');
return next();
});
/* Routes */
app.use(require('./routes/api.js'));
app.use(require('./routes/meta.js'));
app.use('/test', require('./routes/test.js'));
if (process.env.RUM_MYSQL_DSN) {
app.use(require('./routes/rum.js'));
}
app.use(/^\/v[12]\/assets/, express.static(__dirname + '/../docs/assets'));
if (process.env.SENTRY_DSN) {
app.use(Raven.middleware.express.errorHandler(ravenClient));
}
module.exports.node = (event, context, callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
}),
};
callback(event, app);
};
This is my serverless.yml:
service: serverless-node
provider:
name: aws
region: us-east-1
stage: dev
runtime: nodejs6.10
functions:
node:
handler: service/index.node
events:
- http:
path: node
method: get
I think you need to pass back the response object in the callback in the handler e.g.
callback(null, response);
I have my server.js file working. at localhost:8080 it will serve the file i give it from the the corresponding url name like so http://localhost:8080/about.html, as long as the file exists in public/pages. I'm wondering if I can somehow set a wildcard to leave of extensions for all html files in the url so that I don't have to individually specify each file as an alias in the routes like - ['about','about.html'].
Here is my working code -
'use strict';
const Path = require('path');
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({
port: Number(process.argv[2] || 8080),
host: 'localhost'
});
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: 'public/pages',
listing: true
}
},
config: {
state: {
parse: false, // parse and store in request.state
failAction: 'ignore' // may also be 'ignore' or 'log'
}
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
Any help is greatly appreciated, thank you.
I am trying to get a https loopback server up and running protected by OAuth. I am using the loopback gateway sample project as a reference. But for some reason I can't get the OAuth piece to work. What I mean is, even after adding in the OAuth bits and pieces, the APIs don't seem to be protected. I get a response back even if there is no token in my request. This is what my server.js looks like
var loopback = require('loopback');
var boot = require('loopback-boot');
var https = require('https');
var path = require('path');
var httpsRedirect = require('./middleware/https-redirect');
var site = require('./site');
var sslConfig = require('./ssl-config');
var options = {
key: sslConfig.privateKey,
cert: sslConfig.certificate
};
var app = module.exports = loopback();
// Set up the /favicon.ico
app.middleware('initial', loopback.favicon());
// request pre-processing middleware
app.middleware('initial', loopback.compress());
app.middleware('session', loopback.session({ saveUninitialized: true,
resave: true, secret: 'keyboard cat' }));
// -- Add your pre-processing middleware here --
// boot scripts mount components like REST API
boot(app, __dirname);
// Redirect http requests to https
var httpsPort = app.get('https-port');
app.middleware('routes', httpsRedirect({httpsPort: httpsPort}));
var oauth2 = require('loopback-component-oauth2')(
app, {
// Data source for oAuth2 metadata persistence
dataSource: app.dataSources.pg,
loginPage: '/login', // The login page url
loginPath: '/login' // The login processing url
});
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Set up login/logout forms
app.get('/login', site.loginForm);
app.get('/logout', site.logout);
app.get('/account', site.account);
app.get('/callback', site.callbackPage);
var auth = oauth2.authenticate({session: false, scope: 'demo'});
app.use(['/protected', '/api', '/me', '/_internal'], auth);
app.get('/me', function(req, res) {
// req.authInfo is set using the `info` argument supplied by
// `BearerStrategy`. It is typically used to indicate scope of the token,
// and used in access control checks. For illustrative purposes, this
// example simply returns the scope in the response.
res.json({ 'user_id': req.user.id, name: req.user.username,
accessToken: req.authInfo.accessToken });
});
signupTestUserAndApp();
//var rateLimiting = require('./middleware/rate-limiting');
//app.middleware('routes:after', rateLimiting({limit: 100, interval: 60000}));
//var proxy = require('./middleware/proxy');
//var proxyOptions = require('./middleware/proxy/config.json');
//app.middleware('routes:after', proxy(proxyOptions));
app.middleware('files',
loopback.static(path.join(__dirname, '../client/public')));
app.middleware('files', '/admin',
loopback.static(path.join(__dirname, '../client/admin')));
// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.middleware('final', loopback.urlNotFound());
// The ultimate error handler.
app.middleware('final', loopback.errorHandler());
app.start = function(httpOnly) {
if(httpOnly === undefined) {
httpOnly = process.env.HTTP;
}
server = https.createServer(options, app);
server.listen(app.get('port'), function() {
var baseUrl = (httpOnly? 'http://' : 'https://') + app.get('host') + ':' + app.get('port');
app.emit('started', baseUrl);
console.log('LoopBack server listening # %s%s', baseUrl, '/');
});
return server;};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
function signupTestUserAndApp() {
// Create a dummy user and client app
app.models.User.create({username: 'bob',
password: 'secret',
email: 'foo#bar.com'}, function(err, user) {
if (!err) {
console.log('User registered: username=%s password=%s',
user.username, 'secret');
}
// Hack to set the app id to a fixed value so that we don't have to change
// the client settings
app.models.Application.beforeSave = function(next) {
this.id = 123;
this.restApiKey = 'secret';
next();
};
app.models.Application.register(
user.username,
'demo-app',
{
publicKey: sslConfig.certificate
},
function(err, demo) {
if (err) {
console.error(err);
} else {
console.log('Client application registered: id=%s key=%s',
demo.id, demo.restApiKey);
}
}
);
});
}
I don't get any errors when the server starts up. Thoughts?
Got it figured. More information here https://github.com/strongloop/loopback-gateway/issues/17, but basically I had my rest-api middleware not configured right.
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.