I read a tutorial about export/require in node/express and wonder if someone could explain to me with my example: why is my routing in app.js not working? What would I have to export and require to make it work? Thanks a lot!
index.js:
'use strict'
var express = require('express');
var app = express();
module.exports = app;
var PORT = process.env.PORT || 1337;
app.listen(PORT, function() {
console.log('Server is listening!');
})
app.js:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
//var app=require('./index.js');
module.exports = function() {
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.static(path.join(__dirname, '../browser')));
}
var app = express()
.But anyway, if you would like to use this example and make it work, let's do in in this way:
./ index.js
'use strict'
var express = require('express');
var setupServing = require('./setupServing.js'); //import our function
var PORT = process.env.PORT || 1337;
var app = express(); //create express app
setupServing(app); //call imported function to config our app
app.listen(PORT, function() { //start
console.log('Server is listening!');
})
./ setupServing.js
var express = require('express');
var path = require('path');
//export function which can configure static serve for app
module.exports = function(app) { //take app as an argument
app.use(express.static(path.join(__dirname, '../public')));
}
Note that this example still is not logical enough and I don't think you will face such code in any real project, but anyway it will work and demonstrate exporting/requiring in nodejs.