Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping routes in Express

We can group our routes like this in Laravel:

Route::group("admin", ["middleware" => ["isAdmin"]], function () {       Route::get("/", "AdminController@index");      Route::post("/post", ["middleware" => "csrf", "uses" => "AdminController@index");  }); 

Basically, all the routes defined in admin group gets the isAdmin middleware and group name automatically. For example, post endpoint listens to admin/post not /post

Is there any way to do the same thing with Express? It would be awesome because my Laravel routes used to be so clean, whereas my Express routes are a bit messy/duplicated.

This is my routes.js on Express at the moment.

app.get("/admin", [passportConfig.isAuthenticated, passportConfig.isAdmin], AdminController.index); app.post("/admin", [passportConfig.isAuthenticated, passportConfig.isAdmin], AdminController.postIndex); 

Thank you.

like image 408
Aris Avatar asked Aug 11 '16 10:08

Aris


People also ask

Can we use multiple routes in one application?

js allows us to create multiple routes on a single express server. Creating multiple routes on a single server is better to practice rather than creating single routes for handling different requests made by the client.

How do routes work in Express?

A route is a section of Express code that associates an HTTP verb ( GET , POST , PUT , DELETE , etc.), a URL path/pattern, and a function that is called to handle that pattern.

How many middlewares you can use in Express?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app. METHOD() .


1 Answers

Since express 4 you can define and compose routers

const app = require('express'); const adminRouter = app.Router();  adminRouter.use(isAdmin); adminRouter.get('/', admin.index); /* will resolve to /admin */ adminRouter.post('/post', csrf, admin.index); /* will resolve to /admin/post */  app.use('/admin', adminRouter);  

Hope that helps!

like image 93
Melle Avatar answered Sep 25 '22 23:09

Melle