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

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.



Solution 1:[1]

You have to catch any possible promise rejections because if it rejects and you don't have a handler for it, then you will get this error and you won't have done anything intelligible with the error:

getTshirt().catch(err => {
    console.log(err);
    // do something with the error here
});

In the example, you show above, it appears you are getting some sort of NetworkError when trying to access your api_url. So, you'll have to look into the reasons for that error and attempt to fix why it's getting that error in the first place. But, even still, you should always be catching promise rejections.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jfriend00