The localhost server at port 5000 seems to be stuck in a perpetual loading state and is not displaying the

Currently, I am in the process of learning Node.js and have successfully created a server using express documentation in the past. However, for a new project, I decided to incorporate some npm packages such as dotenv, http-errors, ejs, and more. I established a (.env) file where I declared PORT=5000, imported it into my (main.js) file, and executed the app.listen function. Despite my efforts, when I try to access http://localhost:5000 in the browser, it endlessly loads with no content displayed. Surprisingly, there are no errors shown in the terminal; it simply continues loading until I manually terminate the process.

Main.js

const express = require("express");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const path = require("path");
const cookieParser = require("cookie-parser");
const { notFoundHandler, errorHandler } = require("./middlewares/common/errorHandler");

const app = express();
dotenv.config();

// Database connection
mongoose.set("strictQuery", true);
mongoose.connect(process.env.MONGO_CONNECTION_STRING, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
.then(() => console.log("Database Connected!"))
.catch(err => console.log(err));

app.use(express.json);
                  
app.use(express.urlencoded({ extended: true }));

app.set("view engine", "ejs");
app.set('views', 'views');

app.use(express.static(path.join(__dirname, "public")));

app.use(cookieParser(process.env.COOKIE_SECRET));
  
app.use(notFoundHandler);

// Common error handler
app.use(errorHandler);

app.listen(process.env.PORT, () => {
  console.log(`App is listening at port ${process.env.PORT}`);
});

Errorhandler.js

const createError = require("http-errors");

function notFoundHandler(req, res, next) {
  next(createError(404, "CONTENT WAS NOT FOUND!"));
}

function errorHandler(err, req, res, next) {
  res.render("error", {
    title: "Error Page",
  });
}

module.exports = {
  notFoundHandler: notFoundHandler,
  errorHandler,
};

Error.ejs - My ejs file route ("./views/error.ejs")

<title><%= title %></title>
<body>
    Alert!
</body>

.env file

PORT=5000

Answer №1

Issue resolved! I found the solution in my primary document. A missing parentheses() was causing the problem.

The correct code is app.use(express.json());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmit messages from server (via Expressjs routing) to the client

I am looking for guidance on how to effectively send messages from the server to the client and incorporate this functionality into routes/index.js within my mean stack project. Can anyone provide insights on using socket.io in this context?: router.post( ...

Retrieving a certain file from a module in NodeJS

A module called simpledblayer-mongo has been recently created. The functionality of this module relies on another one called simpledblayer, which provides specific functions for the database. An issue has arisen during unit testing. The problem pertains t ...

Exploring the Distinctions: Comparing Socket and Web Server with

This code snippet demonstrates a socket-based example, sourced from the Node.js website. const socketServer = net.createServer((socket) => { socket.end('goodbye\n'); }).on('error', (err) => { // Error handling goes here ...

Error: The Node Express Server is unable to locate the requested resource at "/

const http = require("http"); const myApp= require('./myApp'); const portNumber = 8080; const myServer = http.createServer(myApp); myServer.listen(portNumber) ...

Steps for defining local variables accessible across all EJS templates:1. Begin by creating a helper function

When setting local variables in the /login router as shown in the code snippet below: res.locals.username = data[0].username;, I have checked the output using console.log for both data[0].username and res.locals.username, and it correctly displays the user ...

Stream events are not being recorded for reading an empty file within a timeout period

I'm currently developing code that involves reading from a file and incorporating timeout functionality. I've encountered some issues specifically related to empty files. In the absence of a timeout, the output would typically display something ...

Having trouble getting Node.js DEBUG=appname to work with nodemon on Windows?

I am currently following a Node.js tutorial by Mosh and I'm having trouble getting this line of code to work: DEBUG=app:db nodemon index.js When I try to run it, I encounter the error message: 'DEBUG' is not recognized as an inter ...

Error encountered while attempting to send SendGrid email to multiple recipients

Currently, I am using const sgMail = require('@sendgrid/mail'); with sendgrid version 7.6.2. Whenever I attempt to add two email addresses in an array and then pass it into either send() or sendMultiple(), an error is being thrown like below. st ...

"Combining Node.js, MongoDB, and Vue.js to create a dynamic dependent select dropdown: a step-by-step

Seeking guidance on setting up a dynamic dependent dropdown list using node js, mongoDB and Vue js. As a newcomer to this concept, I'm unsure where to begin. Here is the scenario I am facing: I need assistance in creating 2 dropdown menus for country ...

I was surprised by how Await behaved in if-else statements, it was not what

let metadata = []; allNFTs.map(async (e) => { if (e.metadata) { metadata.push(JSON.parse(e.metadata).attributes); } else { let config = { method: "get", url: `http://localhost:3000/api/fetch ...

Creating an object with an array of objects as a field in MongoDB: A step-by-step guide

I have a unique schema here: const UniqueExerciseSchema = new Schema({ exerciseTitle: { type: String }, logSet: [{ weight: { type: Number }, sets: { type: Number }, reps: { type: Number }, }], }); After obtaining the da ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

What alternatives are available to eliminate the need for body-parser?

After successfully installing the express module and body-parser, I realized that I can now utilize express to gather all necessary information from the user without the need for body-parser. How can I safely remove body-parser from my configuration? cli ...

Guide to changing the status code to 404 for a 404-page in Next.js

I have been trying to figure out how to set a 404 status code for the 404-page in Next.js. The response I received stated that the status code is already 404 by default, but upon closer inspection, it seems that all bad requests are returning a 404 status ...

npm unable to retrieve Meteor package

When I attempted to install meteorite using nodejs v0.10.22 and npm v1.3.14, the installation failed with the following error: $ npm install meteorite npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm ...

Live feed of Npm child processes

I'm currently developing a command-line tool for a node.js application that requires running npm commands and displaying the results. Here's what I've come up with so far: import {spawn} from 'child_process'; let projectRoot = &a ...

How would you execute a simple protractor test with the provided file hierarchy?

I have attempted to follow a tutorial located HERE for running protractor tests. Despite my efforts, I am facing an issue where the tests do not seem to run when I attempt to start them. While my webdriver-manager is functioning correctly, nothing seems to ...

Mastering the Art of Integrating API and JSON!

I've developed a bot using botkit and the Zendesk API to retrieve information. There's a function in my bot that prompts the user for a search term, searches for relevant information using the Zendesk API, and displays the result. I'm faci ...

Retrieving IAM policy for App Engine resource

In my GCP project, I have an App Engine app resource. I currently manage users and roles on the App Engine app using Identity-Aware Proxy in the console. Now, I want to programmatically manage users in IAP. At the moment, I am able to retrieve the IAM pol ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...