I'm trying to do nodejs app for API, using Express 4. But when I make app more modular, my routes doesn't work. Can anybody explain me what is my error and what should be correct structure of application for API ?
My app.js file (some unnesessary code was cut):
var app = express();
var v1 = require('./routes/v1/index');
app.use('/api/v1', v1);
app.use('/api/v2', function(req, res, next) {
console.log('API Version 2');
next();
});
app.use('/api', function(req, res, next) {
console.log('Request of API versions');
next();
});
My routes/v1/index.js file:
var express = require('express');
var router = express.Router();
var user = require('./user');
module.exports = router;
My routes/v1/user.js file:
var express = require('express');
var router = express.Router();
router.route('/')
.get(function(req, res, next) {
console.log('USERS GET');
})
.post(function(req, res, next) {
console.log('USERS POST');
})
.put(function(req, res, next) {
console.log('USERS PUT');
})
.delete(function(req, res, next) {
console.log('USERS DELETE');
});
router.use(function(req, res, next) {
console.log('USERS last Middleware');
});
module.exports = router;
When I try to request such url: http://localhost:3000/api/v1/user
I see in console only message: "Request of API versions" - so no code was triggered in index.js or user.js,
But If I remove user.js and put handling of requests to index js (router.route('...') from user.js in this case located in index.js) - all warks fine, I see messages depending VERB and there is no "Request of API versions" message.
So my question: why it happens? Why user.js not included and doesn't work if I connect it from index.js, how in this case I will make modular app? Put all handling in index.js - is not good, cos I will need /user, /news, /comment etc handling which I suppose will handle in separate files.