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.
Related
Im using react-pdf library in Next.js to generate PDF, view PDF and download that PDF in a Static Client Side Next.js Application (Server is not involved). But I can't set up the Webpack for Next.js as I don't have much knowledge about it.
This is what the required setup for Webpack is for react-pdf:
const webpack = require('webpack')
module.exports = {
/* ... */
resolve: {
fallback: {
process: require.resolve('process/browser'),
zlib: require.resolve('browserify-zlib'),
stream: require.resolve('stream-browserify'),
util: require.resolve('util'),
buffer: require.resolve('buffer'),
asset: require.resolve('assert'),
},
},
plugins: [
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
],
/* ... */
}
And this is the next.config.js:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Important: return the modified config
return config
},
}
That config parameter that next.config.js gives us is like that objet we export in a normal webpack.config.js. Try with this setup of next.config.js:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.fallback = {
process: require.resolve("process/browser"),
zlib: require.resolve("browserify-zlib"),
stream: require.resolve("stream-browserify"),
util: require.resolve("util"),
buffer: require.resolve("buffer"),
asset: require.resolve("assert"),
};
config.plugins.push(
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
process: "process/browser",
})
);
return config;
},
};
Try to place setupProxy.js file in src directory. It content
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app, req, res) {
const options = {
target: 'http://serverurl.com',
changeOrigin: true,
pathRewrite: function(path, req){
// console.log('path BEFORE trans: %o', path);
const p = path.replace('/api', '');
// console.log('current_path: %o', p);
// if(path.indexOf('manage') !== -1){
// p = '/web-module-backend'+p;
// }
// console.log('PATH: %o', p);
return p;
},
onProxyRes: (proxyRes, req, res) => {
// log original request and proxied request info
const exchange = `[${req.method}] [${proxyRes.statusCode}] ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path}`;
// console.log(req.headers);
// console.log(proxyRes.headers);
console.log(exchange); // [GET] [200] / -> http://www.example.com
console.log('Req URL: ' + req.originalUrl);
console.log('Response status code: ' + proxyRes.statusCode);
res.headers = proxyRes.headers;
},
onProxyReq: (proxyReq, req, res) => {
Object.defineProperty(proxyReq, 'headers', {
get(){
return {
host: 'http://urlserver.com',
authorization: 'Authstring', // req.headers.authorization,
}
},
set(){
}
})
console.log(proxyReq.headers);
},
onError: (err, req, res, target) => {
console.log(err);
}
}
const uiProxy = createProxyMiddleware(options)
app.use(
'/api',
uiProxy
);
};
I need to pull in configs from secrets manager before wiring up my proxies
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const { SecretsManagerClient, GetSecretValueCommand } = require('#aws-sdk/client-secrets-manager');
const pjson = require('../app/config');
const app = express();
async function getSecretsManager(){
return secrets; // (this functions correctly, redacting for security)
}
const buildProxies = async (app) => {
const proxies = pjson['nonprod-proxies'];
const secrets = await getSecretsManager();
let proxiesToMap = [];
proxies.forEach(proxy => {
console.log(`[PROXY SERVER] Creating proxy for: ${proxy['proxy-path']}`);
let target, headers, options;
const rewrite = `^${proxy['proxy-path']}`;
if (proxy['internal'])
{
target = `https://${secrets['apiDomain']}`;
headers = {'x-api-key': secrets['apiKey']};
options = {
target: target,
changeOrigin: true,
logLevel: 'debug',
headers
}
} else {
target = proxy['proxy-domain'];
options = {
target: `https://${target}`,
changeOrigin: true,
logLevel: 'debug',
pathRewrite: {
[rewrite]: ''
}
}
}
proxiesToMap.push({'path': proxy['proxy-path'], 'options': options})
});
return proxiesToMap;
};
module.exports = function(app){
buildProxies().then(proxies => {
proxies.forEach(proxyVal => {
console.log(`Proxy: ${proxyVal['path']} with options ${proxyVal['options']}`);
app.use(proxyVal['path'], createProxyMiddleware(proxyVal['options']))
});
});
console.log('=== SUCCESSFULY CREATED PROXY SERVER ===');
};
This results in localhost:3000 returning the boiler plate html cors response, however, when substituting the code for module.exports to be:
app.use('/internal/*', createProxyMiddleware({
target: '<my aws secret url>',
changeOrigin: true,
logLevel: 'debug',
headers: { 'x-api-key': '<my aws secret api key>' }
}));
The proxy works. Is there a way to do an asynchronous load of configs within setupProxy.js?
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 :)
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() ]
};
I'm a doing a project for school using IBM's bluemix and I'm having trouble finding out where is my error. I have a database in CSV that has some parameters (neighbourhood, number of rooms, area in square meters, etc). I also have a JADE file that contains a form that the user have to fill in. In this form, the user will choose how many rooms he wants and everything else. Then, my app in JAVASCRIPT should be able to run the database based on the choices of the user. However, for some reason, the results are not appearing in the webpage as they should.
Here is my code:
/*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
var fs = require('fs');
var parse = require('csv-parse');
// create a new express server
var app = express();
function seleciona_dados(dados, parametros){
var resultado = {Bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};
for (var i = 1; i < dados.Bairro.length; i++){
if (dados.Bairro[i] == parametros.bairro && dados.quartos[i] == parametros.quartos && dados.area[i] >= Number(parametros.area) && dados.valor[i] <= Number(parametros.valor)){
resultado.bairro.push(dados.bairro[i]);
resultado.quartos.push(dados.quartos[i]);
resultado.area.push(dados.area[i]);
resultado.valor.push(dados.valor[i]);
resultado.endereco.push(dados.endereco[i]);
resultado.img.push(dados.img[i]);
}
}
return resultado;
}
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function(req, res){
res.render('cadastro.jade', { pageTitle: 'Cadastro Usuário'});
});
app.post('/resumo', function(req, res){
// var furfles = req.body;
var parser = parse({delimiter: ';'}, function(err, data){
var dados = {bairro: [], quartos: [], area: [], valor: [], endereco: [], img: []};
for (var i = 1; i < data.length; i++){
dados.bairro.push(data[i][0]);
dados.quartos.push(data[i][1]);
dados.area.push(Number(data[i][2]));
dados.valor.push(Number(data[i][3]));
dados.endereco.push(data[i][4]);
dados.img.push(data[i][5]);
}
dados = seleciona_dados(dados, req.body);
res.render('resumo.jade', {pageData:{ pageTitle: 'Resumo do Pedido do Usuário'}, formData: req.body, imoveis: dados});
});
fs.createReadStream(__dirname+'/static/BD.csv').pipe(parser);
});
The list of apartments selected in the database should appear below the last sentence of this image.Page
You should start your for loops with i = 0 instead of 1. You're missing the first two data records.
I've updated your code to:
- declare jade as your template language
- remove unused code
- implement a dictionary comparison for dados
- initial async load for your CSV database, see load_csv_database
- Use Array.filter and equal_to to filter an the database
/*jslint node: true */
'use strict';
// CONFIGURE EXPRESS
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', 'jade');
// CONFIGURE EXPRESS
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
var fs = require('fs');
var csvParse = require('csv-parse');
var database;
/**
* Loads the CSV filename and parse it as JSON Object
* #param String filename The csv filename
* #param {Function} cb The callback
*/
function load_csv_database(filename, cb) {
fs.createReadStream(filename).pipe(
csvParse({ delimiter: ';' }, function(err, data) {
if (err) {
cb(err);
return;
} else {
var result = {
bairro: [],
quartos: [],
area: [],
valor: [],
endereco: [],
img: []
};
data.forEach(function(e) {
result.bairro.push(e[0]);
result.quartos.push(e[1]);
result.area.push(Number(e[2]));
result.valor.push(Number(e[3]));
result.endereco.push(e[4]);
result.img.push(e[5]);
});
cb(null, result);
}
}));
}
// initial database async load
load_csv_database(__dirname + '/static/BD.csv', function(err, result) {
if (!err)
database = result;
else
console.log('error:', err);
});
function equal_to(origin) {
return function compareTo(target) {
for (var p in origin) {
if (origin.hasOwnProperty(p)) {
if (origin[p] !== target[p]) {
return false;
}
}
}
for (var p2 in target) {
if (target.hasOwnProperty(p2)) {
if (origin[p2] !== target[p2]) {
return false;
}
}
}
return true;
};
}
app.get('/', function(req, res) {
res.render('cadastro', { pageTitle: 'Cadastro Usuário' });
});
app.post('/resumo', function(req, res) {
// use the global variable "database"
var result = database.filter(equal_to(req.body));
res.render('resumo.jade', {
pageData: { pageTitle: 'Resumo do Pedido do Usuário' },
formData: req.body,
imoveis: result
});
});
app.listen(appEnv.port, '0.0.0.0', function() {
console.log('server starting on ' + appEnv.url);
});