Why do I get an Object not found error message when I submit an API request

51 Views Asked by At

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?

error in browser 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?

1

There are 1 best solutions below

0
Bench Vue On

You missed "await fetch('http://localhost:3000/api/ethereum')" in your script.js

Demo

Save as server.js

const express = require('express');

const app = express();

app.get("/api/ethereum", async (req, res) => {
    let url = new URL('https://freetestapi.com/api/v1/animals?search=Lion')
    const response = await fetch(url.href)
    const data = await response.json()
    res.send(data)
});

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Save as script.js

const getData = async () => {
    console.log('Hello from script.js')
    const response = await fetch('http://localhost:3000/api/ethereum')
    const data = await response.json()
    console.log(data)
}

getData()

Install Dependency

npm install express

Run Server

node server.js

Run Client

node script.js

Result

enter image description here