meteorBuzz
meteorBuzz

Reputation: 3200

Configure browserSync with nodejs server

I need help in understanding how to configure the ports for node server and browser-sync.

Within the serevr.js file, the http server is listening on port 3006; server.listen(3006);

I would like browsersync to open the browser and point the address to server port 3006. This is the port the http server listening to. So the address would be localhost:3006

gulpfile.js

gulp.task('serve', function() {
browserSync.init({
    server: {
        baseDir: './dist/'
    },
    port: 3006
 });
});
  1. In the mac terminal, I rungulp. This opens the browser to localhost:3006. Fine.

  2. In another terminal window, I start the node server, nodemon dist/serevr.js

I'm unable to get them to be the same. Either the server will not start because something is already running on port 3006, (step 1), or, the following happens if I start the server first.


Local: http://localhost:3007
External: http://192.168.1.63:3007

How can I get them to work together?

Solution found with help from answers below:

gulp.task('serve', function() {
    browserSync.init({
        port: 3007,
        proxy: {
            target: "localhost:3006",
            ws: true
        }
    });
});

Upvotes: 4

Views: 2760

Answers (2)

timolawl
timolawl

Reputation: 5564

There will essentially be two servers running. One that nodemon operates and one that browser-sync will be operating. Both servers cannot have the same ports.

You need to proxy the port you use for nodemon in the browser-sync configuration section of your gulp file. Thus, you need to have the node server up first before browser-sync can proxy it.

If you need to enable websockets, you can do so by setting ws: true.

This is how it would look like:

gulp.task('browserSync', function () {
    browserSync.init({
        port: 3007, // you can specify the port here
              // can't use the same port that nodemon uses.
        proxy: {
            target: 'localhost:3006', // original port
            ws: true // enables websockets
        }
    });
});

Upvotes: 4

Ivan Davletshin
Ivan Davletshin

Reputation: 109

browserSync.init starts the server. You can't bind to one port twice. Use different ports if you need to run both of servers together.

Upvotes: 0

Related Questions