ExpressJS: require multiple files with app.use()? - javascript

Routing:
app.use('/cms/', require('./routes/index.js'));
app.use('/cms/schools/', require('./routes/schools.js'));
Routes:
/cms/
/cms/schools/
/cms/schools/:schoolId/classes/:classId
Goal: I'd like to split ./routes/schools.js into two files: schools.js and schools_classes.js, to keep a better overview.
Problem: I'd like to keep the prefixed path /cms/schools/, but don't know how to split it correctly.
How can I structure the files to reach the desired goal?
Thanks in advance!
Edit 1:
I tried the following, which is not working (duplicated route prefix):
app.use('/cms/', require('./routes/index.js'));
app.use('/cms/schools/', require('./routes/schools.js'));
app.use('/cms/schools/', require('./routes/schools_classes.js'));

You can do It using the express router:
Routes:
const schoolsRouter = require('./routes/schools');
app.use('/cms/schools', schoolsRouter)
./routes/schools/index.js:
const express = require('express');
const router = express.Router();
router.use('/',require('./schools _controller.js'));
router.use('/:schoolId/classes/:classId', require ('./schools_classes_controller.js'));
module.exports = router;
You can check the entire router docs here: http://expressjs.com/en/4x/api.html#router

Related

Best Practice for Route Architecture

I'm trying to set up routes for my backend. I have two ways that I've tried setting these routes up, and I'm wondering which way fits best practices (or neither?). The differences are minimal, but I'd love to know if there is an objective "best" here.
Here are my attempts:
const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');
router.get('/', flashcardController.readFlashcard);
router.post('/', flashcardController.createFlashcard);
router.patch('/', flashcardController.updateFlashcard);
router.delete('/', flashcardController.deleteFlashcard);
module.exports = router
VS
const express = require("express");
const router = express.Router();
const flashcardController = require('../controllers/flashcardController');
module.exports = (app) => {
router.get('/api/flashcard', flashcardController.readFlashcard);
router.post('/api/flashcard', flashcardController.createFlashcard);
router.patch('/api/flashcard', flashcardController.updateFlashcard);
router.delete('/api/flashcard', flashcardController.deleteFlashcard);
app.use('/', router);
};
Of course, my app.js (entry-point for my backend) file will need to be coded slightly differently for each of these options.
If you believe that the job of a router is to just handle some requests that it receives and it is the job of the calling code to place the router at whatever path the calling code wants it to operate on, then only your first option will do that. This would allow a caller to use these routes in whatever path it wants.
If you want the module that implements the routes to be entirely self-sufficient and install the routes on the path it wants them to be on, then only the second option does that.
I would say that the "usual" and more "flexible" scheme is the first one where the caller places the routes on the path where it wants them. But, you are free to choose whichever style you want.
The second option is not implemented particularly efficiently so it could be improved. No router is needed at all as the routes can be just installed directly on the app object directly. And, repeating /api/flashcard multiple times can be avoided.
For example, the second option could be this:
const controller = require('../controllers/flashcardController');
const routePath = '/api/flashcard';
module.exports = (app) => {
app.get(routePath, controller.readFlashcard);
app.post(routePath, controller.createFlashcard);
app.patch(routePath, controller.updateFlashcard);
app.delete(routePath, controller.deleteFlashcard);
};
Or, even just this:
const controller = require('../controllers/flashcardController');
module.exports = (app) => {
app.route('/api/flashcard')
.get(controller.readFlashcard)
.post(controller.createFlashcard)
.patch(controller.updateFlashcard)
.delete(controller.deleteFlashcard);
};
And, the first one could be simplified to this:
const router = require("express").Router();
const controller = require('../controllers/flashcardController');
router.route('/')
.get(controller.readFlashcard)
.post(controller.createFlashcard)
.patch(controller.updateFlashcard)
.delete(controller.deleteFlashcard);
module.exports = router

Adding a routing file inside another routing file node.js

I want my routes to be like the following:
/
/business
/business/stuff1
/business/stuff2
/business/admin
for /business I want to have a separate file for the routing and functions.
and also for /business/admin I want to have a separate file for the routing and functions.
so what I did is:
app.js
//Business route
const business = require("./business/business");
app.use("/business", business);
This works fine - but when I add in business.js
//admin route
const admin = require("./admin");
app.use("/admin", admin);
I get 404 for some reason.
Depends on what you are exporing from business.js. It should be an instance of express.Router and you have to mount the /admin route on this instance. Example:
// business.js
const admin = require("./admin");
const businessApp = express.Router();
businessApp.use("/admin", admin);
module.exports = businessApp;

Differences between query routes in nextjs using next-routes

I'm working on a project with next.js and Reactjs that uses a lot of different languages. So I need to change the language url. Example:
www.example.com/es/entradas
www.example.com/en/tickets
www.example.com/de/eintrittskarten
To make routes I saw that there is a module that helps me: next-routes
https://github.com/fridays/next-routes
There are a lot of url and I'm working with a CMS, so my clients will be able to add more, so routes can't be harcoded. I thought to pass the url with queries, like this:
const routes = require('next-routes');
module.exports = routes()
.add('index', '/:lang?')
.add('tickets', '/:lang?/:ticket')
.add('hotel', '/:lang?/:hotel');
My surprise (as you might see), it doesn't work because routes doesn't see the difference between these two last routes. If I write:
www.example.com/en/tickets
It will go correctly to my page "tickets" but if I write
www.example.com/en/hotel
It will go again to my page "tickets" and not to "hotel"
Do you know any way about how could I make this?
In my project I have these files related about routes:
server.js
const next = require('next');
const { createServer } = require('http');
const routes = require('./routes');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dir: './src/shared', dev });
const handle = routes.getRequestHandler(app);
app.prepare()
.then(() => {
createServer(handle)
.listen(3001, (err) => {
if (err) throw err;
console.log("> Ready on http://localhost:3001");
});
});
routes.js
const routes = require('next-routes');
module.exports = routes()
.add('index', '/:lang?')
.add('tickets', '/:lang?/:ticket')
.add('hotel', '/:lang?/:hotel');
The request for /en/hotel is going to the "ticket" route because it is actually matching it.
This is because of the : in front of the word "ticket" in the route. A : will turn a section of a route into a parameter with that name.
So instead what you probably want is:
module.exports = routes()
.add('index', '/:lang?')
.add('tickets', '/:lang?/ticket')
.add('hotel', '/:lang?/hotel');

Express.js routing. How to put a default route before all of my existing routes

I'm probably phrasing this question wrong so please bear with me. So right now I have some routes:
localhost:3000/index
localhost:3000/home
localhost:3000/login
localhost:3000/forgot
but before every route in the URL, I want a client name like this:
localhost:3000/client/index
localhost:3000/client/home
localhost:3000/client/login
localhost:3000/client/forgot
Is there a good way to do this without manually changing all the route strings? And again sorry if I'm phrasing this question poorly.
Create a router (router.js) with all those rules defined in it. Then reference in express app:
app.use('/client', require ('./router'));
You router file:
var router = require ('express').Router();
router.use('/index', ...);
...
module.exports = router;

separate(organize) express route

I separated routes for rest api like this. Is there better way to organize router ? or the way I am doing is fine?
app.js
app.use('/api/auth',auth);
app/controllers/auth/index.js
var express = require('express'),
router = express.Router(),
register = require('./register');
router.get('/',function(req,res,next){
console.log("api/auth");
res.send('api/auth');
next();
});
router.use('/register',register);
module.exports = router;
app/controllers/auth/register.js
var express = require('express'),
router = express.Router(),
rootPath = require('app-root-path'),
User = require(rootPath+'/app/models/user');
router.post('/',function(req,res,next){
console.log("api/auth/register");
next();
});
module.exports = router;
Building on swaraj'a answer, you should divide your project files into two folders lib and config. Please note that I'm giving you a generic structure this should be customised according to your project.
Config
It should contain all the configuration files for your project.
lib
It should basically have files like controller.js, routes.js, db-ops.js
controller.js contains and exports all functions required for your program logic.
routes.js contains and exports all the routes
db-ops.js intializes db connections and contains functions that define operations on database.
All these files should be required into your app.js which will reside in your projects root directory.
A typical project structure should look something like this:
lib
-routes.js
-controller.js
-db-ops.js
config
-config.json
app.js
You could create a routes.js which has all the separate routes.
Something like,
module.exports = function (app) {
app.use('/api/route1', require('path/to/route1'));
app.use('/api/route2', require('path/to/route2'));
};
Mount this routes in your main app.js.
require('path/to/routes')(app);
Shameless plug of an example, https://github.com/swarajgiri/express-bootstrap/blob/master/web/routes.js

Categories