Open In App

Understanding the Function of a Wildcard Route in Express.js

Last Updated : 21 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about the Wildcard Route and its functions. Wildcard routes are the default case route. If a client requests a route that does not exist on the server, that particular route will be routed to the wildcard route; it is also known as the Error 404 route.

Approach

Wildcard is an Error 404 route of server-side code. When the request created by the client does not match with any API endpoint of the server, that route will particularly direct to the Wildcard route, which means the requested URL does not exist.

This route should be present after all routes so that the server will only route here when all routes fail.

Similarly, this contains two parameters: one is the URL (in this case, the URL is the astrisk), and the other is the request and response object, where you can check what request has been received and what response you have to send.

Syntax:

app.get("*",(req,res)=>{})

Steps to create Node JS application and install required modules:

Step 1: Make a separate folder called server via following command.

mkdir server

Step 2: Initialize Node Application in it via given command.

npm init -y

Step 3: Install Express JS via given command.

npm i express

Step 4: Create a file for code via given command.

touch server.js

Example: Implementation of above approach in the server.js file

Javascript




// Server.js
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json());
 
app.get("/", (req, res) => {
    console.log("GET Request Successfull!");
    res.send("Get Req Successfully initiated");
})
 
app.get("/user", (req, res) => {
    res.send(`Client is requesting for USER Data`)
})
 
app.get("*", (req, res) => {
    res.send("Error 404 Invalid Endpoint");
})
 
app.listen(PORT, () => {
    console.log(`Server established at ${PORT}`);
})


To run the application type the following command in terminal.

node ./server.js

Output: Verify the result using Postman API testing

Animation


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads