working on a project in which I am trying to call an API using JavaScript. It is probably just a stupid mistake I am overlooking, but does anyone know why I keep getting this 'Object not found' message in the console?
Here is my code, I have an index.js as well a public script.js.
This is my index.js
// import Express library and activate it
import express from "express";
const app = express();
// publish our static frontend files
app.use('/',express.static('./public'))
app.get("/api/ethereum", async (req, res) => {
let url = new URL('https://randomuser.me/api/')
const response = await fetch(url.href)
const data = await response.json()
res.send(data)
});
// Start Express
app.listen(process.env.PORT, () => {
console.log(`Express is now Live.`)
console.log(`Public URL: `+ process.env.PUBLIC_URL)
});
Here is my script.js
const getData = async () =>{
console.log('Hello from script.js')
const response = await fetch('/api/ethereum')
const data = await response.json()
console.log(data)
}
getData()
To make sure it wasn't the actual API not working I tried it with a different API, this Random User API that does not require a key. However the same problem occurs... help?
You missed "await fetch('http://localhost:3000/api/ethereum')" in your script.js
Demo
Save as
server.jsSave as
script.jsInstall Dependency
Run Server
Run Client
Result