How to Solve Error Message ReferenceError: req is not defined in NodeJS application

Posted on

Actually, this article will show how to solve the above error message. The error message is ‘ReferenceError: req is not defined’. Eventually, this article has a relation with another article with the title of ‘How to Solve Error Message Cannot Get / in NodeJS Application’ in this link. The following is the error message upon executing a NodeJS application :

[admin@10 nodejs]$ [admin@10 nodejs]$ node app.js
/home/admin/nodejs/app.js:4
app.get("/",(req,res));
             ^
ReferenceError: req is not defined
    at Object. (/home/admin/nodejs/app.js:4:14)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47
[admin@10 nodejs]$

Actually, it is a part for returning a value as soon as there is a request for a page with the root URL of ‘/’. But apparently, the definition for returning the value upon accessing the root URL of ‘/’ is not correct. The following is the actual content of the script with the name of ‘app.js’ :

const express = require("express");
const app = express();
app.get("/",(req,res));
app.listen(3001);
console.debug("Test NodeJS !");

Actually, whenever there is a GET request from that come into port 3001, it suppose to return the value that will be available in the page. So, the syntax of the above line of code is false. The line of code which is not true is in the following line of code :

app.get("/",(req,res));

Actually, the part (req,res) is a function where there must be a definition of it. So, the following is the solution to solve the problem :

1. Editing the line of code to define it as a full definition of the function as follows :

app.get("/",function (req,res){
res.send("Hello World !");
});

2. Another editing form of the line of code for defining the function exist as follows :

app.get("/",(req,res) => res.send("Hello World !"));

Leave a Reply