Node.js/Express.js App Only Works on Port 3000

后端 未结 16 2203
暖寄归人
暖寄归人 2020-12-12 13:23

I have a Node.js/Express.js app running on my server that only works on port 3000 and I\'m trying to figure out why. Here\'s what I\'ve found:

  • Without specifyi
16条回答
  •  春和景丽
    2020-12-12 13:52

    The following works if you have something like this in your app.js:

    http.createServer(app).listen(app.get('port'),
      function(){
        console.log("Express server listening on port " + app.get('port'));
    });
    

    Either explicitly hardcode your code to use the port you want, like:

    app.set('port', process.env.PORT || 3000);
    

    This code means set your port to the environment variable PORT or if that is undefined then set it to the literal 3000.

    Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION and DEVELOPMENT and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.

    $ PORT=8080 node app.js
    

    In reference to your code example, you want something like this:

    var express = require("express");
    var app = express();
    
    // sets port 8080 to default or unless otherwise specified in the environment
    app.set('port', process.env.PORT || 8080);
    
    app.get('/', function(req, res){
        res.send('hello world');
    });
    
    // Only works on 3000 regardless of what I set environment port to or how I set
    // [value] in app.set('port', [value]).
    // app.listen(3000);
    app.listen(app.get('port'));
    

提交回复
热议问题