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.
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.
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.
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() .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With