javascript - Cannot Load Routes in ./src/routes/index.js from ./app.js -


very new nodejs here. i've tried put routes in app.js without problem. however, after moving routes separate file under project_dir/src/routes/index.js, , open page in browser says "cannot /wines". here's code in app.js , src/routes/index.js:

// app.js var express = require('express'); var app = express(); var path = require('path');  global.app = express(); require('./src/routes/index'); // tried: require(path.join(__dirname, './src/routes/index'));  global.server = app.listen(3000, '0.0.0.0', function () {   var host = server.address().address;   var port = server.address().port;    console.log('example app listening @ http://%s:%s', host, port); }); 
// ./src/routes/index.js // tried console.error(app); , printed stuff app in server log app.get('/wines', function(req, res) {   res.send([{name:'w1'}, {name:'w2'}]); });  app.get('/', function (req, res) {   res.send('hello world!'); }); 

i'm sure i'm missing something. appreciated!

problem

honestly, not sure why doing not work.

the file can found because otherwise, node throw error, , fact can access app routes file means app accessible.

i have suspicion may due garbage collection -- because not hold reference module, may preemptively destroyed.

what's more, there construct in express called router probably exists exact purpose.

solution

while i'm not sure problem am sure solution -- use router, this:

var express = require('express');  var router = express.router();  router.get('/wines', function(req, res) {   res.send([{name:'w1'}, {name:'w2'}]); });  router.get('/', function (req, res) {   res.send('hello world!'); });  module.exports = router; 

and in app.js file, this:

var routes = require('./routes/index'); app.use('/', routes); 

another benefit of routers not have pollute global object anymore..


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -