app.set('port', port) 'TypeError: undefined is not a function'. Beginner, need ideas

后端 未结 6 932
春和景丽
春和景丽 2021-02-04 04:12

I\'m an amateur learning to build with node.js. I\'ve been following a tutorial to create my first node.js app. It worked perfectly until I entered \'npm start\'. The log is:

相关标签:
6条回答
  • 2021-02-04 04:48

    In my case I simply moved the normalizePort function before the function was called. This was in coffeescript but I've converted it to javascript here.

    normalizePort = function(val) {
      var port;
      var port;
      port = parseInt(val, 10);
      if (isNaN(port)) {
        return val;
      }
      if (port >= 0) {
        return port;
      }
      return false;
    };
    
    port = normalizePort(process.env.PORT || '4000');
    
    0 讨论(0)
  • 2021-02-04 04:51

    Intaned of calling export please use module.export end the end of your script.

    exports = app;
    module.exports = app;

    0 讨论(0)
  • 2021-02-04 04:52

    At the bottom of your app.js:

    app.set('port', process.env.PORT || 26398); //<--- replace with your port number
    
    // Server
    var server = http.createServer(app);
    server.listen(app.get('port'), function(){
        console.log('Express server listening on port ' + app.get('port'));
    });
    
    module.exports = app;
    
    0 讨论(0)
  • 2021-02-04 05:09

    You are not exporting anything in the app.js file. At the end of app.js file, include following line.

    module.exports = app;
    

    See whether your problem goes away.

    And one more addition: you have var app = express(); twice in your app.js.

    0 讨论(0)
  • 2021-02-04 05:12

    Just add "module.exports=app;" in the app.js file.

    0 讨论(0)
  • 2021-02-04 05:15

    You don't have declared any function called set inside the app.js file. Create that function and export it like this:

    exports.set = function(...) { ... };
    

    If this app is the express app yo especify a port like this:

    var express = require('express'),
        http = require('http');
    
    var app = express();
    
    http.createServer(app).listen(port);
    

    instead of

    app.set('port', port);
     /**
     * Create HTTP server.
     */
    
    var server = http.createServer(app);
    

    This is because the port is a property of the http server and not of the express app

    You can use also

    var express = require('express'),
        app = express();
    
    app.listen(port);
    
    0 讨论(0)
提交回复
热议问题