Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express module exports

im getting this error

app.get is not a function

this is my config/express.js

var express = require('express');


    module.exports = function(){

    var app = express();

    app.set('port',3000);

    return app;

    };

and this is my server.js

var http = require ('http');

var app = require ('./config/express');


http.createServer(app).listen(app.get('port'), function(){

    console.log("Express Server Runing on port"+ app.get('port'));


});

what im doing wrong?

like image 667
John Avatar asked Feb 13 '17 13:02

John


People also ask

What is module exports in node JS?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.

What can you export with Module exports in node JS?

Module exports are the instruction that tells Node. js which bits of code (functions, objects, strings, etc.) to “export” from a given file so other files are allowed to access the exported code.

What can you export with module exports?

By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.

What is the difference between module exports and exports?

exports and module. exports both point to the same object. exports is a variable and module. exports is an attribute of the module object.


1 Answers

in config/express.js you export a function but use it as an app. Try this instead:

var express = require('express');
var app = express();
app.set('port', 3000);
module.exports = app;

Edit: But the following is preferred:

/* config/express.js */
var express = require('express');
module.exports = function() {
  var app = express();
  app.set('port', 3000);
  return app;
};


/* server.js */
var http = require('http');
var app = require('./config/express')(); // Notice the additional () here

http.createServer(app).listen(app.get('port'), function() {
    console.log("Express Server Runing on port"+ app.get('port'));
});
like image 191
Tamas Hegedus Avatar answered Sep 23 '22 14:09

Tamas Hegedus