[node.js] How to get Node.JS Express to listen only on localhost?

I have an application that I have behind a reverse proxy, I would like for it to only listen to localhost/127.0.0.1.

I expected this to work:

app.listen(3001, 'localhost');

or

app.listen(3001, '127.0.0.1');

...but instead I get an error:

node.js:201
    throw e; // process.nextTick error, or 'error' event on first tick
          ^
TypeError: Cannot read property 'port' of null
    at Object.<anonymous> (/home/ctoledo/hive-go/go.js:204:76)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

Running the application without a specifying the hostname works fine, ie., app.listen(3001);.

I am running Node v0.6.14 and express@2.5.5 and have read this google groups discussion and have found this comment in Express application.js saying: "This method takes the same arguments as node's http.Server#listen()."

Thanks for any help.

This question is related to node.js express

The answer is


Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.


Questions with node.js tag:

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean` jwt check if token expired Using Environment Variables with Vue.js Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Can not find module “@angular-devkit/build-angular” MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client npx command not found await is only valid in async function What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? How to set bot's status Returning data from Axios API Error: EACCES: permission denied, access '/usr/local/lib/node_modules' ReferenceError: fetch is not defined ERROR in Cannot find module 'node-sass' Test process.env with Jest 'react-scripts' is not recognized as an internal or external command NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0' db.collection is not a function when using MongoClient v3.0 When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0) E: Unable to locate package npm How can the default node version be set using NVM? How to downgrade Node version How to solve npm install throwing fsevents warning on non-MAC OS? How to read file with async/await properly? Angular: Cannot Get / The difference between "require(x)" and "import x" Is there a way to force npm to generate package-lock.json? Angular - ng: command not found MongoError: connect ECONNREFUSED 127.0.0.1:27017 How can I use async/await at the top level? ERROR in ./node_modules/css-loader? Downgrade npm to an older version Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51 npm install Error: rollbackFailedOptional npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY How can I use an ES6 import in Node.js? Node.js: Python not found exception due to node-sass and node-gyp bash: npm: command not found? npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json' Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Questions with express tag:

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js sequelize findAll sort order in nodejs Typescript import/as vs import/require? nodemon not working: -bash: nodemon: command not found Push items into mongo array via mongoose NodeJS accessing file with relative path Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response How to send a POST request from node.js Express? Start script missing error when running npm start How to provide a mysql database connection in single file in nodejs What is the difference between res.end() and res.send()? SyntaxError: expected expression, got '<' Understanding passport serialize deserialize TypeError: Router.use() requires middleware function but got a Object pass JSON to HTTP POST Request Purpose of installing Twitter Bootstrap through npm? Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused Proper way to set response status and JSON content in a REST API made with nodejs and express res.sendFile absolute path Sending JWT token in the headers with Postman How can I include css files using node, express, and ejs? req.body empty on posts POST request not allowed - 405 Not Allowed - nginx, even with headers included bodyParser is deprecated express 4 How to modify the nodejs request default timeout time? How can I set response header on express.js assets Node/Express file upload Basic HTTP authentication with Node and Express 4 Error: No default engine was specified and no extension was provided How to use Morgan logger? How to call a Python function from Node.js Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port How to generate unique ID with node.js Error: getaddrinfo ENOTFOUND in nodejs for get call File uploading with Express 4.0: req.files undefined What does "res.render" do, and what does the html file look like? Express.js Response Timeout Failed to load c++ bson extension create a trusted self-signed SSL cert for localhost (for use with Express/Node) Cannot GET / Nodejs Error ENOENT, no such file or directory