Unhandled error in Express JS API causing undefined responses

I am a beginner in JavaScript and I have started using Express to create a REST API for the backend of my current project. However, I am encountering an issue where the API is returning undefined or the fetch statement in my main.js file seems to be altering the response. Below is the relevant backend code:

import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());
app.use(express.json());
app.use((req, _, next) => {
    console.log(req);
    next();
  });
//setting up express.js

//handling requests
app.get('/', async (_, res) => {
    res.send({ url:'https://gifdb.com/images/high/you-got-rick-rolled-rick-astley-dance-2s99zcvywfvs3kao.gif' });
});

//start the server
app.listen(8080, () => console.log('http://localhost:8080/'));

Here is the code responsible for fetching the data:

const response = await fetch('http://localhost:8080/', {
      method: 'GET',
    });


    const { image } = await response.json();

    console.log(image)

    const result = document.querySelector('#result');
    result.innerHTML = `<img src="${image}" width="512" />`;

Answer №1

The use of const { image } in the code snippet is an example of a technique known as destructuring assignment. In this case, it attempts to extract the image property from the result of await response.json();, which is actually undefined.

A better alternative would be:

const image = (await response.json()).url;
console.log(image);

OR

const { url } = await response.json();
console.log(url);

Answer №2

When setting up the communication between the server and browser, ensure consistency in naming conventions. For example, if you named the property for the image URL as url on the server, make sure to reference it as url on the browser as well.

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

Emphasize table cells dynamically

Query How can I dynamically highlight a selected td? Codepen Example View Pen here Code Snippet The map consists of a randomly generated 2D array, like this: map = [[1,1,1,1,0], [1,0,0,0,0], [1,0,1,1,1], [1,0,0,0,1], [1,1, ...

Creating a custom calculator using Javascript

As a beginner in Javascript, I am seeking assistance in creating a simple calculator that can add numbers as buttons are clicked and display the running total. For example: If I click the button "20," it should display the number 20. Then, if I click the ...

Adding negative values to the Tailwind CSS utility plugin is a simple process that can greatly enhance

Adding Negative Values to Tailwind CSS Utility Plugin Quick Summary: I've developed a custom Tailwind utility plugin that includes numeric values. I'm looking for a way to introduce negative numbers by adding a - at the start of the class, simi ...

Conceal a div while revealing the other div

I am currently trying to achieve a unique visual effect. I have three divs named div1, div2, and div3. The objective is for div1 to slide up and disappear when clicked, while div2 simultaneously slides up and becomes visible. Similarly, when div2 is click ...

Implementing validation and displaying fields with v-model in vue.js

Looking at this code snippet: <button type="button @click="editing=true">Edit</button> <form v-show="editing" @submit="onSubmit"> <textarea v-model="text"></textarea> </form> <div> Current value: {{text}} </ ...

Watching an array of objects in AngularJS with assigned indices

I'm seeking guidance on how to utilize Angular watch with an array of objects. Here is an example array $scope.chartSeries containing objects like this: [{"location": {values}, "id":"serie-1", "meter":{values}, "name": "seriename", "data":[{1,2,4,5, ...

Retrieve information from the API prior to rendering the controller components

Hello there! I am looking to retrieve data from a factory before any of my controllers are loaded. After some research, I discovered that it can be achieved using the resolve function in AngularJS: angular.module('agent', ['ngRoute',&a ...

Utilizing Node JS to transfer information from an array of objects into a Postgres table

After spending the entire day trying to work with JSON data and Postgres, I still can't figure out what's causing the issue. This is a snippet of my dataset, consisting of around 1000 objects: { avgHighPrice: null, highPriceVolume: 0, ...

The Rails text area fails to load through JavaScript when a line break is detected

My comment form has a feature that displays the content of the text area using js. It functions properly unless a new line is entered in the text area, in which case it does not show up right away. However, after refreshing the page, the comment appears wi ...

Utilizing custom i18n blocks for Vue 3 and Vuetify 3 to enhance locale messages

Looking to localize messages separately for each component? Check out this example for Vue 2. But how can it be done for Vue 3 and Vuetify 3? Here's what I've tried: package.json "dependencies": { "@mdi/font": "6.5 ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

Deletion of input is not permitted

Currently, I have a telephone input field on my form that only allows numbers. I have implemented a simple JavaScript code to enforce this validation. However, the issue I am facing now is that the input box cannot be deleted. <form id="aylikal" action ...

Is there any benefit to making the SVG elements width and height 100%?

The Angular Material documentation app features an SVG Viewer that is able to scale the SVG content to fit the container using the following function: inlineSvgContent(template) { this.elementRef.nativeElement.innerHTML = template; if (this.sca ...

arrange according to a specific sequence

I have been working on developing a JavaScript card game. I am looking for a way to match four consecutive numbers in a list. Currently, I have a loop structure that seems complex: cards = [{card:'h7'},{card:'c8'},{card:'h ...

Validating the end points of a Node Express API integrated with MySql

Currently, I am developing an API using express that interacts with a MySQL database to store user credentials securely. One of the main functionalities of my API includes endpoints for user registration and login. Testing these endpoints in Postman has s ...

Ensuring Email Validation in MERN Application

I'm looking for guidance on how to implement email verification during the signup process in MERN Stack. I would like to send an email containing a link that redirects users to a specific page. Below is my node.js code for sign up - can anyone advise ...

My script works perfectly during $(document).ready(function() execution on a local server, but encounters issues when run

I am facing an issue with my $(document).ready(function() code that only seems to work locally. I'm not sure what the problem is, but here is an example of the code. Thank you for any assistance. <a href="#"><img src=images/folder_icon.png i ...

Unable to preventDefault() function from working within .then method

Snippet: angular .module('mean-starter') .run(run) ; function run($rootScope, Auth, $state) { function stopStateChange (message, event, redirect) { console.log(event); event.preventDefault(); alert(message); if (redirect) ...

Converting JSON data to CSV format with JavaScript

I have been attempting to convert a JSON object to CSV using JavaScript, but the results are not as expected. UPDATE: The JSON object is stored in a variable, and every time I try to access 'list', it returns as undefined. Is there a way to acce ...

The code generated by Asto SSR may not be compatible with older iOS versions, causing it to fail to run

I have been running my astro SSR site on Netlify with great success. However, I recently encountered an issue when testing it on older iPhone models like the iPhone 6 and earlier. It seems that all script executions halt, rendering the site non-interactive ...