Amy T McBride Amy T McBride - 4 months ago 19
Node.js Question

express server not serving to correct port

I have the following code in my app's app.js file:

var express = require('express');
var path = require('path');
var fs = require('fs');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
var secrets = require('./routes/secrets');

var app = new express();

// Set listening port
app.set('port', 8080);

// Create write stream and append to log file
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// routes
app.use('/', routes).listen;
app.use('/users', users).listen;
app.use('/secrets', secrets);
app.use('/secret', secrets);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// set trust proxies + serving IPs
app.set('trust proxy', function(ip) {
if (ip === '127.0.0.1' || ip === '139.162.246.138') return true;
else return false;
});

// error handlers

// development error handler
// will print stacktrace
pp.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;


Which should surely be serving to port 8080. However, when I try to run the server, this happens every time:

[root@fedora hackapp]# DEBUG=hackapp:* npm start

> hackapp@1.1.0 start /root/ColourHack1-1/hackapp
> node ./bin/www

Port 3000 is already in use


Any ideas what's causing this to happen? I'm serving from a Fedora 24 server on a Linode if that's making any difference. I already have an Angular2 project serving from port 3000, so freeing the port up isn't an option.

Answer

Setting a port through app.set('port') actually doesn't tell express to use this port when creating a server, it serves just for storing the port value and then you can get it with app.get('port') in other parts of your app.

You should look into /bin/www as it's the start point of your app and see where the port is set there and change the default port to app.get('port').

Comments