Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen.

app.get("/", (req, res, next) => {
  console.log("middleware");
  const error = true;

  if (error) {
    next();
  }
});

app.use((err, req, res, next) => {
  res.status(400).json({ error: "error description" });
});

In this code, I replicated that if an error occurs, send an object, but it only sends "cannot get". When inspecting the body section in POSTMAN, I am only seeing HTML code with the "cannot get" message. What could be the issue here? Could you please provide an explanation?

When using POSTMAN, all I can see is this HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /</pre>
</body>

</html>

Answer №1

The error handler will not be triggered because no error is passed to the next() function. This results in receiving a 'Cannot GET /' message since the first route handler does not send a response.

According to the Express documentation:

If errors arise from asynchronous functions called by route handlers and middleware, they must be passed to the next() function for Express to handle and process them accordingly.

To ensure proper functionality, simply pass the error to the next() function as shown in your example:

app.get("/", (req, res, next) => {
  console.log("middleware");
  const error = new Error('bad things just happened');
  
  if (error) {
    next(error);
  }
});

app.use((err, req, res, next) => {
  res.status(400).json({ error: "error description" });
});

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

Tips for loading images dynamically (or lazily) as they come into the user's view with scrolling

Many modern websites, such as Facebook and Google Image Search, display images below the fold only when a user scrolls down the page enough to bring them into view (even though the page source code shows X number of <img> tags, they are not initially ...

What is a method to mimic the presence of JavaScript using PHP Curl?

Is it possible to parse HTML code from a webpage using PHP Curl even if there is an error message stating that JavaScript is required to access the site? Can PHP Curl be used to enable JavaScript on a webpage? ...

What is the reason behind JavaScript events causing a page refresh?

My code uses RegExp to search through an array of strings based on user input: Clinica.prototype.pesquisarDoente = function () { var exp = document.getElementById("pesquisaInput").value; var lista = document.getElementById("listaDoentes"); if ...

Structure of RESTful API Routes

Struggling to determine the most RESTful route for my API. To provide some context, I am working on an API for a sweepstakes application with a hierarchy of client, sweepstakes, and submission. I'm unsure of the best approach for creating new sweepst ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Put a cookie in place to deter users from returning to the website

Looking for a way to prevent access to my contest site once the form has been submitted. Is there a way to achieve this? Thanks in advance ...

What are the steps to create an Angular 8 application with a node backend and deploy it on Firebase?

My goal is to create a web scraper using node and then transfer that data to my angular front end. I am interested in hosting this Progressive Web App on firebase because of its user-friendly interface and cost-effectiveness. This will be my first attempt ...

Creating a callback function within stored procedures using JavaScript Language Integrated Query in documentDB: A step-by-step guide

According to the documentation, the code snippets below are considered equivalent. However, I have observed that in the first case, I am able to perform operations on multiple documents within the callback function, whereas the map function in the latter s ...

Error: Failed WebSocket connection to 'wss://wechat.pageguy.tech/socket.io/?EIO=3&transport=websocket' due to an unexpected response code 302.nginx + socket.io + ssl:WebSocket connection to 'ws://wechat

Trying to set up a node.js project with socket.io using nginx and ssl, but encountering errors when starting it. The error message is as follows: I've spent hours searching and reading documentation, but still haven't found a solution. If anyone ...

React JS component experiencing issues with Material UI modal functionality

Attempting to reproduce the material ui modal example has proven to be a challenge for me. Initially, I encountered an error stating "Cannot read property 'setState' of undefined" which I managed to resolve. However, even after resolving this iss ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

What causes getServersideprops to return undefined?

The data I am trying to fetch is showing as undefined in the console. Here is the code snippet: export default function Home({ data }) { console.log(data); return ( <div> <h2>Welcome !!</h2> </div> ); } export a ...

Is there a solution available for the error message that reads: "TypeError: Cannot set value to a read-only property 'map' of object '#<QueryCursor>'"?

Everything was running smoothly in my local environment, but once I deployed it on a Digital Ocean Kubernetes server, an error popped up. Any assistance would be greatly appreciated. https://i.stack.imgur.com/VxIXr.png ...

Result is not defined after aggregating in MongoDB with Mongoose framework

I am struggling to retrieve comments from a MongoDB collection (using Mongoose) and compute the total number of comments as well as the average rating using the aggregate pipeline. However, if the initial $match query returns no results, the script crashes ...

Trigger function in a different child component on mouse up

Trying to call a function in a child component from another child component in ReactJS. Specifically, I want to trigger a function in another component when the 'mouseup' event happens. Here is an illustration of what I am attempting to achieve: ...

Generate dynamic DIV elements and populate them with content

Can you assist me in getting this code to function properly? My goal is to dynamically create elements inside a div and fill each element with a value fetched from the database through a server-side function. I'm unsure if there's a better approa ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

Having trouble getting Typescript code to function properly when using commonjs style require statements

I am completely new to Typescript, Node.js, and Express. Following the instructions outlined in this tutorial (https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript), I set up my project exactly as described there. The ...

Executing npx command with organized packages

When attempting to execute a scoped package with npx, I am running into some issues. It seems like the only way to do it is by specifying the package directly, like so: npx -p @foo/bar bar This command will successfully download @foo/bar and execute the ...

Exploring the world of Express, EJS, and Node.js

What is the method to generate a page containing a button that, when clicked with onclick(), redirects users to another webpage? ...