Express.JS Create A Route in Separate File

Code Snippets 4 U

Below is the code of ourpage.js with a get request handler and param id. We used express.Router() function to create a route in separate file.

var express = require('express') // import express module 
var route1 = express.Router() // create a object of Route 
route1.get('/:id', function(req, res) { // handle get request with id as a param 

    res.send(req.params.id); // send the response after reading the param 
})
module.exports = route1 // export the module

Below is the code of our main.js which will handle our all request.

var express = require('express') // import express module 
var app = express() // create module 
var ourPageModule = require("./ourpage.js") // import our module 
app.use('/routeName', ourPageModule) // now use the use() method of express app to point the 'routeName' towards the our module. Its kind of binding. app.listen(80)

Now we can call http://host:port/routeName/id

Leave a Reply

Your email address will not be published. Required fields are marked *

seventy three + = 76