How to Create Separate Routes File in Node JS Express?

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Hello Brother,

Hello Brother, node js routes in separate file is our main topic. if you want to see lesson 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 lessons 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.

Lesson 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!");

});

}

Result:-

localhost:3000/users

Simple Call users Route from Here!

localhost:3000/posts

Simple Call posts Route from Here!

Lesson 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);

};

Result:-

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

thank you very much for following up with me.

Tags

Recent Posts

Related Posts