How to Create Separate Routes File in Node JS Express?
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Node JS Express Route with Parameters Example
- How to Create Route in Node JS Express JS?
- How to Generate 4,6,8,10 Digit Random number in Node JS?
- Node JS Read and Write Json File Example
- Node JS Find and Update Object in Array Example
- How to Get Data from Json File in Node JS?
- How to Remove Element from Array in Node JS?
- How to Push Element in Array in Node JS?
- How to use Underscore JS in Node JS App?
- Node JS Sort Array of Objects by Value Example
- Node JS Foreach Loop Array Example