Problem Statement: On running a Node.js application URL on the web browser it throws the following error:
Cannot GET/
Example: Let’s create a simple Node.js application that throws the same error.
Step 1: Initializes NPM: Create and Locate your project folder in the terminal & type the command
npm init -y
It initializes our node application & makes a package.json file.
Step 2: Install Dependencies: Locate your root project directory into the terminal and type the command
npm install express
To install Express as dependencies inside your project
Step 3: Create Server File: Create an ‘app.js’ file, inside this file require an express Module, and create a constant ‘app’ for creating an instance of the express module.
const express = require('express') const app = express()
Step 4: Create a Message Route: Create a get route using app.get() method which sends “hello” as a text to the web browser.
app.get("/messages", (req, res) => { res.send("Hello"); });
Step 5: Set up a port to run our server: We will do it by using the express, app.listen() method.
app.listen(3000, () => { console.log("listening on http://localhost:3000"); })
Complete Code:
const express = require( 'express' )
const app = express() app.get( "/messages" , (req, res) => {
res.send( "Hello" );
}); app.listen(3000, () => { }) |
Output:
Reason: Since in the server file, we create a get route for ‘/messages’ URL but inside the browser, we try to get the ‘/’ URL which is not specified in our server file that’s why it throws the error.
Solution Approach: We have to set up a universal route, and when any route or URL which are not specified inside the server file will call then the universal URL sends a “404 URL NOT FOUND” message.
app.get("/:universalURL", (req, res) => { res.send("404 URL NOT FOUND"); });
Complete Code:
const express = require( 'express' )
const app = express() app.get( "/messages" , (req, res) => {
res.send( "Hello" );
}); app.get( "/:universalURL" , (req, res) => {
res.send( "404 URL NOT FOUND" );
}); app.listen(3000, () => { }) |
Output: