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
On the server, you named the property for the image URL
url
, but on the browser, you’re referencing it asimage
. You’ll need to change them to match.The
const { image }
is a destructuring assignment which tries to find theimage
property fromawait response.json();
which is obviouslyundefined
.The code should be:
OR