Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid URL | TypeError

Tags:

javascript

When clicking the button on my front end (relevant portion shown below)

async function getSample() {
  const res = await fetch('/lookup/url');
  const data = await res.text();
  console.log(data);
}
document.getElementById('button').addEventListener('click', getSample);

async function getSample() {
  fetch('http://localhost:3000/lookup/url')
    .then(response => response.text())
    .then(data => console.log(data));
}

I am getting this error in the terminal of my node server:

TypeError [ERR_INVALID_URL]: Invalid URL: url

and this in my console:

Fetch failed loading: GET "http://localhost:3000/lookup/url"

Can anyone provide some advice as to what I may be doing wrong and how I could fix?

Not that this matters, but backend is express

Adjustment Re: Comments

async function getSample() {
    const res = await fetch('/lookup/url');
    const data = await res.text();
      console.log(data);
    
      document.getElementById('button').addEventListener
       ('click', getSample);
    
        fetch('http://localhost:3000/lookup/url')
        .then(response => response.text())
        .then(data => console.log(data));
    }
like image 415
Max.California Avatar asked Aug 03 '26 10:08

Max.California


1 Answers

Get rid of the second definition of getSample(). You only need one definition of the function, and it's better to use a relative URL to access resources on the same server as the front end.

async function getSample() {
  const res = await fetch('/lookup/url');
  const data = await res.text();
  console.log(data);
}
document.getElementById('button').addEventListener('click', getSample);
like image 153
Barmar Avatar answered Aug 09 '26 13:08

Barmar