Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express JS API Returning Undefined

I am new to Javascript and am using Express to make a REST API for the backend of a project I’m working on. However, for some reason, either the API returns undefined or the fetch statement in my main.js file is somehow changing it to be that. Here is the backend code in question:

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();
  });
//setup express.js

//what to do when someone pings us
app.get('/', async (_, res) => {
    res.send({ url:'https://gifdb.com/images/high/you-got-rick-rolled-rick-astley-dance-2s99zcvywfvs3kao.gif' });
});

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

And here is the code that fetches it:

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" />`;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The const { image } is a destructuring assignment which tries to find the image property from await response.json(); which is obviously undefined.

The code should be:

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

OR

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading