Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource

Viewed 1451

So this is my api code, I am trying to request this api through script.js on my frontend, but I get an error.

var express = require("express");
var app = express();
const cors = require('cors')
port = 8080

app.use(cors(
    {
        origin: "*",
    }
))


app.get('/tshirt', (req, res) =>{
    res.status(200).send({
        tshirt: '',
        size: 'large'
    })
})

app.post('/tshirt/:id', (req, res) => {
    
    const { id } = req.params;
    const { logo } = req.body;

    if (!logo) {
        res.status(418).send({message: 'We need a logo!'})
    }
    
    res.send({
        tshirt: ` with your ${logo} and ID of ${id}`,
    })

})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
  })

and this is the fetch request in script.js

const api_url = 'localhost:8080/tshirt'
async function getTshirt() {
    const response = await fetch (api_url);
    const data = await response.json();
    const { tshirt, size } = data;
    console.log(size)
    console.log(tshirt)
}

getTshirt()

But then I get this error

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
    getTshirt http://127.0.0.1:5500/script.js:3
    <anonymous> http://127.0.0.1:5500/script.js:10

I have tried googling this and looking all over the site but no solutions work. Please help.

0 Answers
Related