skip to Main Content

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

2

Answers


  1. On the server, you named the property for the image URL url, but on the browser, you’re referencing it as image. You’ll need to change them to match.

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search