I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code:

  try {
        const res = await fetch("/api/email-registration", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            emailValue: emailValue,
          }),
        })

        if (!res.ok) throw new Error(res.status);
        const data = await res.json();
        setMessage(data.message)
      } 
      catch (err) {
        console.log(err)
   
      }

The post request is functioning properly. However, I am now attempting to access the error response JSON when intentionally creating an error to trigger the catch (err) block.

One of the predefined error messages is:

res.status(409).json({
          message: "This email has already been registered",
        })

In the network tab, I can see the response status 409 and the response JSON with the specified value. When trying err.message, only 409 is returned. My goal is to access the JSON value

{"message":"This email has already been registered"}
.

Is there a method to retrieve the error response message?

I simply want to display this specific JSON message to the user. Until now, I have used an if statement to check for 409 and display text based on the status code. However, I am interested in finding a way to access and display the JSON message from the post request error.

Answer №1

You mentioned:

if (!res.ok) throw new Error(res.status);

To obtain the response, it is essential to properly handle it.

For example, you can try something like this (Note: This code is untested and provided as a rough outline).

if (!res.ok) {
    try {
        const data = await res.json();
        const message = {
            status: res.status,
            message: data
        }
        throw new Error(JSON.stringify(message));
    } catch (e) {
        const message = {
            status: res.status,
            message: "Could not parse body as JSON"
        }
        throw new Error(JSON.stringify(message));
    }
}

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

What is causing the issue with updating the user in MongoDB using this code?

Currently, I am working on fetching a team's schedule from an excel file and then adding those shifts to the user's shifts in MongoDB. I have tried adding them to an object first and then to the user's shifts field, but nothing seems to be h ...

Choose components identified by a dot

If I have a simple script that displays an element based on the option selected, how can I handle periods in the values? For instance: <select id="my-selector"> <option value="cat.meow">Cat</option> <option value="dog.bark"> ...

Tips on invoking Bootstrap's collapse function without using JQuery

We are facing a challenge with our TypeScript files as we have no access to jQuery from them. Our goal is to trigger Bootstrap's collapse method... $(object).collapse(method) but without relying on jQuery. Intended Outcome //Replicates the functio ...

Discover the process of attaching an event to the keyboard display within a Cordova application

I've exhausted my efforts trying to figure out how to assign an event for when the virtual keyboard appears on my hybrid cordova app. I'm looking to trigger a specific action whenever the keyboard shows up in my app consistently. ...

Loading images efficiently using JavaScript

While working on my JavaScript exercises, I encountered something strange with the image slider script I was creating. When trying to change the image source using the 'setAttribute' method in the HTML code, I noticed that the source of the imag ...

Skipping the configuration file during the process of converting Node.js files to an executable using pkg

I am currently working on a node.js application and in order to prevent users from reading the code, I am attempting to convert my JavaScript files to executable files. I have been using the pkg module for this task, but I have encountered an issue. The p ...

Iterate through each key in the response JSON object using a variable named "a

Here is a snippet of my code: var roomid= roomIds[i] const Availabilitydata = await AvailResponse.json(); availableroomsArray.push(Availabilitydata); app.get("/api/availability", (req, res) => { res.json({ indicateur: availableroomsA ...

What are the steps to create offline documentation for sails.js?

I am looking to integrate offline sails.js documentation into my system. You can find the official documentation for sails.js maintained at this Sails.js Documentation. According to their documentation, they use doc-templater for building the documentati ...

What is the process for setting up the Google Maps API within an Angular application without relying on any directives

Currently, I am attempting to integrate Google Maps into the application that I am developing. Utilizing the Places API for certain functionalities has been successful thus far. However, I have encountered an issue when trying to display a map on a specifi ...

Discovering the mean value from a data set in a spreadsheet

I have been tasked with creating an HTML page for a car dealership using JQuery and Bootstrap 5. The goal is to utilize Bootstrap 5 to accomplish the following: Set up a table with appropriate form input elements that allow users to input four (4) quarter ...

Requesting information asynchronously returns a positive response

I wrote the following code: if (venue_exists(instagramUserID)){ alert('A'); }else { alert('C'); } function venue_exists(instagramUserID) { $.get( "/venues/" + instagramUserID, function( ...

Breaking down a intricate JavaScript expression in order to reformat it into a different structure

As I explore the task of refactoring a legacy application, I find myself faced with complex JavaScript expressions stored in a database column. These expressions contain validation and conditional rendering logic that need to be translated into structured ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Switching between light and dark mode in Chakra UI Next Js takes an extra tap on Mobile devices to update the Background Color

I encountered an unusual issue while trying to set up a ColorMode Toggle on a NextJs project using Chakra UI for light and dark modes. After following the documentation and implementing it accordingly, I noticed that everything works as expected on deskto ...

Ember 2: Display a loading message only if the IDs were part of the initial response

I frequently use the following code snippet in my projects: {{#each model.posts as |post|}} <div>post.title</div> {{else}} <div>Loading the posts...</div> {{/each}} However, I sometimes face uncertainty regarding whether t ...

Try using an outer function within the useEffect hook to handle cases where you receive

When using the useEffect hook, I encountered an issue where I received a TypeError: searchCharacters(...) is undefined error when trying to execute a function outside of the component called searchCharacters for API search requests. Can anyone help me unde ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...

Obtain the name of a node using its identification number in D3JS

I am currently working on implementing a generalized tooltip feature. This tooltip will display the name and other relevant data of the active node. For example, if node 3 is currently active, the tooltip will show the name and distance (not link distance) ...

Automate the execution of webdriver/selenium tests when a form is submitted

I am currently faced with a challenge in setting up an application that will automate some basic predefined tests to eliminate manual testing from our workflow. The concept is to input a URL via a user-friendly form, which will then execute various tests ...