Browser-sync [proxy error] ECONNREFUSED on initial load ONLY - gulp

I am getting a really weird behaviour with my gulp and browser-sync setup.
When I run my gulp serve task the gulp task runs and build everything and opens the web browser, it just stays there spinning. I go to check the console and I'm getting this error.
[gulp-bs] Watching files...
[gulp-bs] [proxy error] connect ECONNREFUSED
Mongoose connected to mongodb://localhost/<database name>
Now what is interesting is when I go and hit that URL with the browser bar to load the application, everything loads properly.
Why does it happen only the first time but subsequent reloading the browser URL works?
I can't seem to figure out what is causing this error, I don't want to keep reloading the browser after the initial load.
My gulp setup for browser-sync is shown below:
"gulp": "^3.9.0",
"browser-sync": "^2.7.13"
The function is called from a nodemon gulp-task.
function serve(isDev) {
var options = {
script: config.nodeServer,
delayTime: 1,
env: {
"PORT": config.port,
"NODE_ENV": isDev ? "dev" : "production"
}
};
$.nodemon(options)
.on("restart", function(ev) {
log("*** nodemon restarted.");
log("files changed on restart: " + ev);
setTimeout(function() {
browserSync.notify("Reloading now...");
browserSync.reload({
stream: false
});
}, config.browserReloadDelay);
})
.on("start", function() {
log("*** nodemon started.");
startBrowserSync(isDev);
})
.on("crash", function() {
log("*** nodemon crashed due to unexpected reason(s).");
})
.on("exit", function() {
log("*** nodemon exited successfully!.");
});
}
Browser-sync function:
function startBrowserSync(isDev) {
log("*** Starting browser sync");
if (browserSync.active || args.nosync) {
return;
}
if (isDev) {
gulp.watch([config.styles], ["styles"])
.on("change", function(event) {
changeEvent(event);
});
gulp.watch([config.js], ["wiredep"])
.on("change", function(event) {
changeEvent(event);
});
} else {
gulp.watch([config.styles, config.js, config.html], ["optimize", browserSync.reload])
.on("change", function(event) {
changeEvent(event);
});
}
var options = {
proxy: "localhost:" + config.port,
port: 8000,
files: isDev ? [
config.client + "**/*.*",
"!" + config.styles,
config.css + "**/*.css"
] : [],
ghostMode: {
clicks: true,
scroll: true,
location: false,
forms: true
},
injectChanges: true,
logFileChanges: true,
logLevel: "debug",
logPrefix: "gulp-bs",
notify: true,
reloadDelay: 1,
};
browserSync(options);
}
The config.port value is set to 3000 read from a configuration file.

Related

Running multiple instances of browserSync

Browsersync detects only index.html and auto refresh can be applied only to this file. But how can I use browsersync for pages like about.html or comments.html etc. ???
If those pages are not linked to from your index.html but are in the same directory you can start browserSync at the folder level with:
server directory options.
// Serve files from the app directory with directory listing
server: {
baseDir: "src",
directory: true
}
and then open each in a new tab if you want them all open at the same time.
If you want to open multiple web pages at once when starting your gulp task you would have to start multiple instances of browserSync each with its own index:
server: {
baseDir: "./",
index: "about.html",
},
Here is how to start multiple instances of browserSync:
// the create "string" can be anything useful
var browserSync = require("browser-sync").create("index.html");
var browserSync2 = require("browser-sync").create("about.html");
var reload = browserSync.reload;
var reload2 = browserSync2.reload;
// a function since I am using gulp4.0 but could be a task as well
function serve(done) {
browserSync.init({
port: 3000,
server: {
baseDir: "./",
index: "index.html",
},
// open: false,
ghostMode: false
});
browserSync2.init({
// need to increment the port manually it appears
port: 3003,
// and must increment the ui port as well
ui: {
port: 3004
},
server: {
baseDir: "./",
index: "about.html",
},
// open: false,
ghostMode: false
});
done();
}
And you will need something like:
gulp.watch("./*.html").on("change", reload);
gulp.watch("./*.html").on("change", reload2);
which could be refactored into a single function call that does both. And also any reload calls would needed to be replicated like:
function sass2css() {
return gulp.src(paths.sass.stylesFile)
.pipe(sass().on("error", sass.logError))
.pipe(gulp.dest(paths.css.temp))
.pipe(reload({ stream:true }))
.pipe(reload2({ stream:true }));
}
so that both index.html and about.html's css are reloaded.
Which should also be refactored but that will have to wait.

gulp-connect developer server give no response when connect-history-api-fallback is used in middleware

I’m trying to use 'connect-history-api-fallback' with gulp-connect like this:
var gulp = require('gulp'),
connect = require('gulp-connect'),
historyApiFallback = require('connect-history-api-fallback');
gulp.task('server', function() {
connect.server({
root: 'app',
livereload: true,
middleware: function(connect, opt) {
return [ historyApiFallback ];
}
});
});
However, the server http://localhost:8080/ gives no response. No errors in the terminal, merely get timeout in browser.
When I remove middleware like bellow, everything is perfect:
gulp.task('server', function() {
connect.server({
root: 'app',
livereload: true
});
});
The API has changed.
The correct way of using connect-history-api-fallback now the following:
var gulp = require('gulp'),
connect = require('gulp-connect'),
historyApiFallback = require('connect-history-api-fallback');
gulp.task('server', function() {
connect.server({
root: 'app',
livereload: true,
middleware: function(connect, opt) {
return [ historyApiFallback({}) ];
}
});
});

Gulp BrowserSync and npm start

I'd like to start my NodeJS application using BrowserSync but it seems not working.
Error message : Error: listen EADDRINUSE
Edit #1:
I found this way to resolve my issue.
gulp.task('sync', ['start', 'watch'], function(cb) {
browserSync.init({
files: ['**/*'],
proxy: 'http://localhost:3000',
port: 4000
});
});
gulp.task('start', function() {
var called = false;
return nodemon({
script: './bin/www',
watch: ['Application.js']
}).on('start', function onStart() {
if (!called) {
cb();
}
called = true;
}).on('restart', function onRestart() {
setTimeout(function reload() {
browserSync.reload({
stream: false
});
}, 500);
});
});
EADDRINUSE means that the port number which listen() tries to bind the server to is already in use. So, in your case, there must be running a server on port 80 already. If you have another webserver running on this port you will get the EADDRINUSE error.
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('default', ['browser-sync'], function () {
});
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:5000",
files: ["**/*.*"],
browser: "google chrome",
port: 7000,
});
});
gulp.task('nodemon', function (cb) {
nodemon({
script: './bin/www/app.js'
})
.on('start', function () {
cb();
})
.on('error', function(err) {
// Make sure failure causes gulp to exit
throw err;
});
});
Hope it helps :)

Using browsersync as dev webserver combined with node app serving only api and not static files

I'm currently using gulp webserver with following config.
gulp.task('webserver', ['nodejs'], function () {
return gulp.src(config.client)
.pipe(webserver({
livereload: true,
port: 8001,
proxies: [
{
source: '/api',
target: 'http://localhost:3007/api'
}
],
directoryListing: false,
open: true
}));
});
So, it serves the static files and proxies request starting with /api to a nodeJs app on another port.
I want to do now the same with Browser-sync (instead of using livereload, so I want to get rid of gulp webserver), but don't find how I can configure this.
Thanks for giving some guidance.
Ok,I found a potential solution (please comment if you have improvements)
var browserSync = require('browser-sync');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
gulp.task('bs', ['nodejs'], function () {
browserSync({
server: {
baseDir: "./client"
},
middleware: function (req, res, next) {
var url = req.url;
if (url.substring(0,5)==="/api/") {
proxy.web(req, res, { target: 'http://localhost:3007' });
} else {
next();
}
}
});
});

Gulp plugin for running a PHP server?

I'm looking to transition over from grunt to gulp. However I'm not finding a way to serve PHP files with livereload support, such as gateway (https://www.npmjs.org/package/gateway) using mounts. Are ther any plugins out there for running/server PHP using a gulp task?
I asked totally the same question few weeks ago. I want to start a native PHP server under Gulp, because I like the syntax better than Grunt. I also want to use PHP just to include other HTML files. :) It turns out there is a 'gulp-connect-php' plugn which has a very similar syntax to 'grunt-php' plugin.
https://www.npmjs.com/package/gulp-connect-php
https://www.npmjs.com/package/grunt-php
Here is my code to Gulp:
var gulp = require('gulp'),
livereload = require('gulp-livereload'),
connectPHP = require('gulp-connect-php');
gulp.task('connect', function() {
connectPHP.server({
hostname: '0.0.0.0',
bin: 'C:/php/php.exe',
ini: 'C:/php/php.ini',
port: 8000,
base: 'dev',
livereload: true
});
});
I also setted the exe and ini file location.
If you interested in, this is the code for Grunt:
php: {
watch: {
options: {
livereload: true,
bin: 'C:/php/php.exe',
ini: 'C:/php/php.ini',
base: '../development',
port: 8000
}
}
}
I hope it helps!
I ended up using gulp-connect-php with http-proxy. In the end, my php serve task looked like this:
gulp.task('php-serve', ['styles', 'fonts'], function () {
connect.server({
port: 9001,
base: 'app',
open: false
});
var proxy = httpProxy.createProxyServer({});
browserSync({
notify: false,
port : 9000,
server: {
baseDir : ['.tmp', 'app'],
routes : {
'/bower_components': 'bower_components'
},
middleware: function (req, res, next) {
var url = req.url;
if (!url.match(/^\/(styles|fonts|bower_components)\//)) {
proxy.web(req, res, { target: '{ip address taken out}:9001' });
} else {
next();
}
}
}
});
// watch for changes
gulp.watch([
'app/*.html',
'app/*.php',
'app/scripts/**/*.js',
'app/images/**/*',
'.tmp/fonts/**/*'
]).on('change', reload);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('app/fonts/**/*', ['fonts']);
gulp.watch('bower.json', ['wiredep', 'fonts']);
});