How do I split up my routes using Express.Router() into multiple files?
You can create a set of routes file (userRoutes.js
, pullRoutes.js
...). In these files, you can use the express.Router class to create modular, mountable route handlers. Then in the main file, you mount all your routers in your Express application.
Example :
- userRoutes.js
const express = require('express');
const router = express.Router();
router.get('/', function (req, res) {
res.send('Get users controller');
});
router.post('/', function (req, res) {
res.send('Post user controller');
});
module.exports = router;
- server.js
const express = require("express");
const app = express();
app.use(express.urlencoded())
app.use(express.json())
const userRoutes = require('./userRoutes');
app.use('/users', userRoutes);
app.listen(80);
In the browser, http://localhost/users
gives me the text Get users controller
Splitting Routes into multiple files
Finally I figured it out:
Install routing for the functions name you need, like:
install(Routing) {
contact()
}
Create a function like fun Route.contact(){ ..}
to handle the requisites, so for my example, I created the below:
fun Route.contact(){
get("/") {
call.respondText("""
My Example Blog 12
<form action="/contact-us" method="post">
<input name="subject" placeholder="Subject">
<br>
<textarea name="message" placeholder="Your message ..."></textarea>
<br>
<button>Submit</button>
</form>
""", ContentType.Text.Html)
}
post("/contact-us") {
val post = call.receive<ValuesMap>() // val userId = registration["userId"]
SimpleEmail().apply {
setHostName("smtp.gmail.com")
setSmtpPort(465)
setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
setSSLOnConnect(true)
setFrom("my_alias@gmail.com")
setSubject(post["subject"])
setMsg(post["message"])
addTo("my_alias@gmail.com")
}.send() // will throw email-exception if something is wrong
call.respondRedirect("/contact-us/success")
}
get"/contact-us/success") {
call.respondText("Your message was sent", ContentType.Text.Html)
}
}
Divide large routes.rb to multiple files in Rails 5
Rails 6.1+ built-in way to load routes from multiple files.
From official Rails docs:
Breaking up very large route file into multiple small ones:
If you work in a large application with thousands of routes, a single config/routes.rb
file can become cumbersome and hard to read.
Rails offers a way to break a gigantic single routes.rb
file into multiple small ones using the draw macro.
# config/routes.rb
Rails.application.routes.draw do
get 'foo', to: 'foo#bar'
draw(:admin) # Will load another route file located in `config/routes/admin.rb`
end
# config/routes/admin.rb
namespace :admin do
resources :comments
end
Calling draw(:admin)
inside the Rails.application.routes.draw
block itself will try to load a route file that has the same name as the argument given (admin.rb
in this case). The file needs to be located inside the config/routes
directory or any sub-directory (i.e. config/routes/admin.rb
or config/routes/external/admin.rb
).
You can use the normal routing DSL inside the admin.rb
routing file, however you shouldn't surround it with the Rails.application.routes.draw
block like you did in the main config/routes.rb
file.
Link to the corresponding PR.
how to properly split express routes into separate files?
OK, after a few more hours of googling & trial/error I finally figured it out. For some reason I didn't find earlier this setup guide but it was pretty much what I wanted.
rails 4: split routes.rb into multiple smaller files
This was removed from Rails 4 in June of 2012. 5e7d6bba reverts an earlier commit, removing support for loading multiple external route files as part of config.rb.
For further read, check out the comments on this commit.
How to split app-routing.module.ts in multiple files in Angular 2?
This would be the AppComponentRoutingModule
which I use, which can be extended with further files, usually that is one routes file per nested routing (to be imported in the corresponding module). The components and routes may vary, but it generally works alike this (guards skipped for the sake of brevity):
Create src/app/routes/app.routes.ts
with content alike:
import { Routes } from '@angular/router';
import { ErrorPage } from 'src/app/pages/error/error.page';
export const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' }, // main entry point.
{ path: 'home', loadChildren: () => import('src/app/pages/home/home.module').then(m => m.HomeModule) },
{ path: 'error/:id', component: ErrorPage, pathMatch: 'full' },
{ path: '**', redirectTo: '/error/404' }
];
The nested routes don't look much different, for example src/app/routes/home.routes.ts
:
export const homeRoutes: Routes = [{
path: '',
component: HomePage,
children: [
...
]
}];
Create src/app/app.component.routing.module.ts
with content alike:
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule } from '@angular/router';
import { appRoutes } from './routes/app.routes';
@NgModule({
imports: [
RouterModule.forRoot(appRoutes,{preloadingStrategy: PreloadAllModules})
],
exports: [ RouterModule ]
})
export class AppComponentRoutingModule {}
Then import AppComponentRoutingModule
in app.module.ts
:
import { RouterModule } from '@angular/router';
import { AppComponent } from 'src/app/app.component';
import { AppComponentRoutingModule } from 'src/app/app.component.routing.module';
...
@NgModule({
declarations: [ AppComponent ],
imports: [
RouterModule,
AppComponentRoutingModule,
...
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
In order to enable verbose logging, enableTracing: true
is your friend.
Splitting routes into separate files
In a seperate file:
import This from '../components/This'
import That from '../components/That'
import ThatOther from '../components/ThatOther'
import ThatOtherOne from '../components/ThatOtherOne'
export default [
{
path: '/this',
name: 'this',
component: This
},
{
path: '/that',
name: 'that',
component: That
},
]
in your route file import the external routes and use the spread oeprator:
import externalRoutesOne from './externalRoutesOne'
import externalRoutesTwo from './externalRoutesTwo'
var router = new Router({
routes: [
...externalRoutesOne,
...externalRoutesTwo
]
Note: the
...
operator is required when defining them routes.
Play Framework: split routes in multiple files without sub projects
Well, the first method is working. I started from scratch and it worked. I did a clean command before the compile command. It seems that old compiled files were the cause of my problem.
Be careful to note that you cannot have an overlap in package names in the routes files. E.g. in this example, the technical.routes
file contains all routes in the controllers.technical
and the main routes file cannot contain any routes in the controllers.technical
package.
conf/routes
contents:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
-> /technical technical.Routes
GET / controllers.Dashboard.index()
conf/technical.routes
contents:
# Routes
# ~~~~
GET / controllers.technical.App.index()
Related Topics
What Does +@ Mean as a Method in Ruby
Ruby.Metaprogramming. Class_Eval
How to Change the Default Value of a Struct Attribute
Getting a List of Classes That Include a Module
Does Ruby Have Syntax for Safe Navigation Operator of Nil Values, Like in Groovy
Obtaining a Facebook Auth Token for a Command-Line (Desktop) Application
Is Regexp.Last_Match Thread Safe
Remove Subdomain from String in Ruby
How to Split a String by Commas Except Inside Parenthesis, Using a Regular Expression
How to Model a Mutual Friendship in Rails
Select Checkbox Pass Array in Ruby on Rails
How Do Version Numbers Work for Mri Ruby
How to Count Existing Instances of a Class in Ruby
Unpermitted Parameters for Dynamic Forms in Rails 4
Simplest Way to Send Raw Byte-Arrays Using Ruby's Tcpsocket-Class