'NodeJS + ExpressJS: What is routes/index.js and its purpose?
What is the purpose of this file?
Is this where 'all' the get and post calls get instantiated?
If so, wouldn't this be a very huge file when working with large scale projects?
I've tried calling a post, /authenticateLogin, from another file other than routes/index.js, but it fails to work, resulting in a 404 error.
routes/login.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('login');
});
router.post('/authenticateLogin', function(req, res){
console.log("Authenticating 2!");
res.send('number two!');
});
module.exports = router;
But it works perfectly when I put it in the index.js file.
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', { title: 'Home' });
});
router.post('/authenticateLogin', function(req, res){
console.log("Authenticating 1!");
res.send('number one!');
});
module.exports = router;
views/login.jade
extends layout
block content
h1 Login
form(method='post' action='/authenticateLogin')
input(type='text' placeholder='username' name='username')
input(type='password' placeholder='password' name='password')
input(type='submit')
Solution 1:[1]
That's where you actually load the framework and define the routes.
Solution 2:[2]
You can spread your routes into several files.
Actually, Dominic Barnes already answered your question.
Solution 3:[3]
In login.js, you can define your routes and to make these routes work, you need to import this file to your index.js.
So in this way if you are working on a large scale project, you can just follow this modular approach and define routes in different files and include all these files in index.js file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guillermo Mansilla |
| Solution 2 | Community |
| Solution 3 | PAVAN BANSAL |
