How to Create Separate Routes File in Node JS Express?

By Hardik Savani June 16, 2021 Category : Node JS

Hi,

Today, node js routes in separate file is our main topic. if you want to see example of node express routes in separate file then you are a right place. you can see how to create separate routes file in node js. i explained simply about separate file for routes in express node.js.

In this tutorial, i will give you two examples of how to create separate routes file in node.js separate project. so let's see both way and you can pick any one that you require.

Example 1:

server.js

var express = require('express');

var app = express();

require('./routes')(app);

app.listen(3000, () => console.log(`App listening on port 3000`))

routes.js

module.exports = function(app){

app.get('/users', function(request, response){

response.send("Simple Call users Route from Here!");

});

app.get('/posts', function(request, response){

response.send("Simple Call posts Route from Here!");

});

}

Output:

localhost:3000/users

Simple Call users Route from Here!

localhost:3000/posts

Simple Call posts Route from Here!

Example 2:

server.js

var express = require('express');

var app = express();

var user = require('./user');

var post = require('./post');

app.get('/users', user.list);

app.get('/user/:id', user.view);

app.get('/posts', post.list);

app.get('/post/:id', post.view);

app.listen(3000, () => console.log(`App listening on port 3000`))

user.js

exports.list = function(request, response){

response.send("Simple Call users Route from Here!");

};

exports.view = function(request, response){

var id = request.params.id;

response.send("Simple Call user id: " + id);

};

post.js

exports.list = function(request, response){

response.send("Simple Call posts Route from Here!");

};

exports.view = function(request, response){

var id = request.params.id;

response.send("Simple Call post id: " + id);

};

Output:

localhost:3000/users

Simple Call users Route from Here!

localhost:3000/user/5

Simple Call user id: 5

localhost:3000/posts

Simple Call posts Route from Here!

localhost:3000/post/5

Simple Call post id: 5

i hope it can help you...

Tags :
Shares