Search code examples
javascriptnode.jsexpressmiddleware

How to setup express routes separate from main file?


I want to follow below file structure to separate my rputes from main app.js i have tried api/user/post api that returns 404 , any idea how can i fix this issue by using below file structure ?

./app.js

var express        = require('express');
var app            = express();
var bodyParser     = require('body-parser');
var db = require('./config/db');
var port = process.env.PORT || 8080;  
app.use(require('./app/routes'));
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); 
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(methodOverride('X-HTTP-Method-Override')); 
app.use(express.static(__dirname + '/public')); 
function startServer() {
  server.listen(port, function() {
    console.log('Express server listening on %d, in %s mode', port, app.get('env'));
  });
}               
setImmediate(startServer);

// expose app           
exports = module.exports = app; 

./app/routes.js

module.exports = function(app) {

    app.use('/api/user', require('./api/user'));
    app.route('*')
        .get(function(req, res) {
            // res.sendFile('./public/views/index.html');
            res.sendfile('./public/views/index.html');
        });
};

./app/api/user/index.js

var express = require('express');
var controller = require('./user.controller');

var router = express.Router();

router.get('/', controller.index);
router.post('/',controller.create);


module.exports = router;

Error

angular.js: 12410 POST http: //localhost:8080/api/user 404 (Not Found)
    (anonymous) @ angular.js: 12410
p @ angular.js: 12155(anonymous) @ angular.js: 11908(anonymous) @ angular.js: 16648
$eval @ angular.js: 17972
$digest @ angular.js: 17786
$apply @ angular.js: 18080(anonymous) @ angular.js: 26749
cg @ angular.js: 3613
d @ angular.js: 3601
angular.js: 14328 Possibly unhandled rejection: {
    "data": "Cannot POST /api/user\n",
    "status": 404,
    "config": {
        "method": "POST",
        "transformRequest": [null],
        "transformResponse": [null],
        "jsonpCallbackParam": "callback",
        "url": "/api/user",
        "data": {
            "firstName": "John",
            "lastName": "Zhang"
        },
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8"
        }
    },
    "statusText": "Not Found"
}

Solution

  • The way, you have defined route in index.js and mounted in routes.js, it will give 404 for /api/user, because when it searches / in index.js, it only finds /api/users only which is accessible by /api/user/api/users.

    You can try to mount userrouter to /api/user and can define / route in index.js

    ./app/api/user/index.js

    var express = require('express');
    var controller = require('./user.controller');
    
    var router = express.Router();
    
    //GET /api/user
    router.get('/', controller.index);
    
    //POST /api/user
    router.post('/',controller.create);
    
    module.exports = router;
    

    ./app/routes.js

    module.exports = function(app) {
    
      //ANY /api/*
      app.use('/api/user', require('./api/user'));
    
      app.route('*')
        .get(function(req, res) {
            // res.sendFile('./public/views/index.html');
            res.sendfile('./public/views/index.html');
        });
      };
    

    Hope it helps you.

    Update

    You have another issue in your code. In your app.js, you defined app.use(require('./app/routes')); while routes.js is function(app).

    Change that line to

    require('./app/routes')(app);
    

    And add that line after app.use(express.static(__dirname + '/public'));