LIAL
LIAL

Reputation: 1634

Correct modular structure of nodejs+express app for API

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.

Upvotes: 2

Views: 906

Answers (2)

whitfin
whitfin

Reputation: 4639

Similar to what Matt said, but not quite;

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

var user = require('./user');
module.exports = router;

This is doing nothing, you need to tell your router to use the 'user' file.

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

router.use('/user', require('./user'));
module.exports = router;

Upvotes: 1

Matt
Matt

Reputation: 13

Your routes/v1/index.js file is exporting a router with no routes/middleware added to it.

In your routes/v1/index.js file could you please try module.exports = user;.

Have you thought about moving the routes inside of routes/v1/user.js into routes/v1/index.js?

(p.s I'm quite new to express)

Upvotes: 1

Related Questions