charliebrownie
charliebrownie

Reputation: 6097

Exporting and requiring Express application issue

Taking the following basic Express: 'Hello World' example as my starting point:

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

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

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('App listening at http://%s:%s', host, port);
});

I'm trying to organize the code in different .js files to separate configuration and routing.

This way I would have app.js:

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

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('App listening at http://%s:%s', host, port);
});

// Expose app
exports = module.exports = app;

and /routes/api.js (having api.js inside a child directory called routes):

var app = require('../app.js');

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

but exports = module.exports = app; and var app = require('../app.js'); are not working: I get the message Cannot GET / all the time when calling the API method.

Upvotes: 0

Views: 42

Answers (1)

Nir Levy
Nir Levy

Reputation: 12953

you should make app.js your 'main' file, and the routes should be inclulded in it.

your route file should look somthing like this:

var express = require('express');
var router = express.Router();

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

module.exports = router;

and to your app.js add:

var api = require("./routes/api.js");
...
//all your code for creating app 
...
app.use('/', api);

Upvotes: 2

Related Questions