NodeJs – Handling invalid routes

While developing Node.Js application it is important to handle invalid routes.
It can be done by writing a custom route or redirecting all the invalid routes to any custom page.

    Let’s develop an simple nodejs server for handling invalid routes:

  • Step 1: Create a project folder
    Create a separate folder for invalid routes project.
  • Step 2: Create package.json
    Package.json will be created by typing the following command in terminal or command prompt:

    npm init -y
  • Step 3: Create a javascript file on the root of the project:
  • Step 4: Create a simple server using express:
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // importing express package for creating the express server
    const express = require('express'); 
    const app = express(); // creating an express object
      
    const port = 8000; //setting server port to 8000
      
    // for mounting static files to express server
    app.use(express.static(__dirname+'public/'));
      
    // listening server
    app.listen(port, function (err) {
        if(err){
            console.log("error while starting server");
        }
        else{
            console.log("server has been started at port "+port);
        }
    })

    chevron_right

    
    

  • Step 5: Define routes

    app.get('/', function (req, res) {
        res.send("Ashish")
    })
    
    app.get('/geeksforgeeks', function (req, res) {
        res.sendFile(__dirname+'/public/geeksforgeeks.html')
    })
    

Now, we will start our server by following command in terminal or command promopt:

 node server.js

If you have nodemon installed in your system then it can also be done by using the following link:
To know more about nodemon and how to use it, please refer: This

nodemon server.js

Here, in our project till now we have developed two routes as:

  • Root route(/)
    This route will be accessed at http://localhost:8000/
  • Geeksforgeeks route(/geeksforgeeks)
    This route will be accessed at http://localhost:8000/geeksforgeeks

Now, let’s try to access a different random route which is not defined in the server file.

As shown in the screenshot we are getting the error while trying to access /india route.

Writing the Custom route for handling all invalid routes:
We will add a route for all invalid routes as shown below:

app.get(‘*’, function(req, res){
res.sendFile(__dirname+’/public/error.html’);
}

Now, the updated server file will be as given below:

filter_none

edit
close

play_arrow

link
brightness_4
code

// importing express package for creating the express server
const express = require('express'); 
const app = express(); // creating an express object
  
const port = 8000; // setting server port to 8000
  
  
app.use(express.static(__dirname+'/public'));
  
// creating routes
app.get('/', function (req, res) {
    res.send("Ashish")
})
  
app.get('/geeksforgeeks', function (req, res) {
    res.sendFile(__dirname+'/public/geeksforgeeks.html')
})
  
app.get('*', function (req, res) {
    res.sendFile(__dirname+'/public/error.html');
})
  
  
// listening server
app.listen(port, function (err) {
    if(err){
        console.log("error while starting server");
    }
    else{
        console.log("server has been started at port "+port);
    }
})

chevron_right


Let’s try to access the same India route for which we were getting Cannot Get /India error

For doing it url will be : http://localhost:8000/india

Now, if we will try to access any random invalid or wrong route we will get that error page as shown above.

    Points to remember:

  • Route for invalid routing should be placed at the last of all routes because routes are called in the order in which they are written.
  • If we will write this route in the starting or in the middle somewhere then all routes which are written after this route will not work and will be redirected to be handled as the invalid route.

Let’s understand this with an example:
We are changing the orders of routes here

filter_none

edit
close

play_arrow

link
brightness_4
code

// importing express package for creating the express server
const express = require('express'); 
const app = express(); // creating an express object
  
const port = 8000; // setting server port to 8000
  
  
app.use(express.static(__dirname+'/public'));
  
// creating routes
app.get('*', function (req, res) {
    res.sendFile(__dirname+'/public/error.html');
})
  
app.get('/', function (req, res) {
    res.send("Ashish")
})
  
app.get('/geeksforgeeks', function (req, res) {
    res.sendFile(__dirname+'/public/geeksforgeeks.html')
})
  
  
  
  
// listening server
app.listen(port, function (err) {
    if(err){
        console.log("error while starting server");
    }
    else{
        console.log("server has been started at port "+port);
    }
})

chevron_right


Now, we will get the invalid route response while accessing any route either it is defined or not in code because we are handling the invalid routes on the top of server.js

So, it is necessary to write the custom route at the end of the all routes so that it will not interfere with the function of any other route.

In this way, we can handle the Invalid routes access in nodejs.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.