Skip to content
Related Articles

Related Articles

Improve Article

Create a route with “search url” as parameter using Express.js

  • Last Updated : 14 Apr, 2021

Express.js is the most powerful framework of the node.js. Express.js is a routing and Middleware framework for handling the different routing of the webpage, and it works between the request and response cycle. Express.js use different kinds of middleware functions to complete the different requests made by the client for e.g. client can make get, put, post, and delete requests these requests can easily handle by these middleware functions. Refer to this article to understand how the Express.js framework works. In this article, we will discuss what is routing and how to create a route using two methods.

Routing: Routing in-network means filtering out the desired path from the bulk of paths available in the computer networks or the server. We can create our own routes with the help of the express.js middleware that routes our path to the desired location.

Working Routing: All incoming requests from the client-side are matched with all the routes available in the project directory. Particular route responds after the matching is successful.

There are two methods to create a route for a particular URL.



  1. Without using express-generator: In this method, we simply use the express.js module to implement the search URL route. Express.js can handle multiple different requests on the same route.
  2. With the use of express-generator: express-generator is the quickest way to generate all the necessary files that are required for making Node.js. Express-generator generates default routes as well as default configured app.js file.

Below is the implementation of both methods:

1 Without express-generator: Use a simple express module that handles all the requests from the client as well as checks the incoming requests. 

Installing module:

npm install express

Project Structure:

index.js




//Importing require module
const express=require("express")
const server_route=require("./search")
const app=express()
  
// Creating First route
app.use("/",server_route);
  
// Listening the server
app.listen(3000,()=>{
  console.log("Server is Running on the port 3000")  
})

search.js




//Importing libraries
var express = require('express');
var router = express.Router();
  
// Handling first request
router.get('/search', function(req, res, next) {
  res.send('Respond from server');
  res.end()
});
// Handling second request of different route
router.get("/search/login",(req,res,next)=>{
    res.send("This is the login page")
    res.end()
})
// Exporting router 
module.exports = router;

Run index.js file using below command:



node index.js

Output: Visit the http://localhost:3000/ it will redirect to you http://localhost:3000/search/login.

2 Using express-generator: express-generator is the quickest way to generate all the necessary files that are required for making web applications. The advantage of this approach is Express-generator generates default routes as well as default configured app.js file.

Installing express-generator:

npm install -g express-generator

Basic express-generator command:

Generator Files in project structure: After installing the express-generator. We have to create a new file search.js in the routes folder of the express-generator folder.

app.js




//Default Imported libraries
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
  
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
  
// creating instance of the search.js route
var searchRouter=require("./routes/search")
  
var app = express();
  
// view engine setup
app.set('views', path.join(__dirname, 'views'));
  
  
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
  
app.use('/', indexRouter);
app.use('/users', usersRouter);
  
// Handling request for the searchRouter
app.use('/',searchRouter)
  
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
  
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
  
module.exports = app;

Run app.js file using below command:

node app.js

search.js




var express = require('express');
var router = express.Router();
  
/* GET users listing. */
router.get('/search', function(req, res, next) {
  res.send('Respond from server');
  res.end()
});
router.get("/search/page",(req,res,next)=>{
    res.send("Respond to the search page")
    res.end()
})
  
module.exports = router;

Console output:

Handling Response:




My Personal Notes arrow_drop_up
Recommended Articles
Page :