0

I'm trying to query data from a Grafana Loki Cloud.

This works:

curl -s -G "https://<user>:<API key>@<site>.grafana.net/loki/api/v1/query_range" --data-urlencode 'query={job="maplejob"}'

credentials in link

If I move it into JavaScript like this

const query_url = new URL('https://<user>:<API key>@<site>.grafana.net/loki/api/v1/query_range');
const params = new URLSearchParams(query_url.search);
params.set('query', '{job="maplejob"}');
query_url.search = params;

fetch(query_url.toString(), {})
    .then((response) => { console.log(response) })
    .catch(console.error);

I get the error:

TypeError: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials

credentials in header

If I move it into JavaScript like this

const query_url = new URL('https://<site>.grafana.net/loki/api/v1/query_range');
const params = new URLSearchParams(query_url.search);
params.set('query', '{job="maplejob"}');
query_url.search = params;

fetch(query_url.toString(), {
    headers: {
        'Authorization': `Basic ${btoa('<user>:<API key>')}`
    },
})
    .then((response) => { console.log(response) })
    .catch(console.error);

I get the error:

Access to fetch at '<query url>' from origin '<current page url>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

What do I do?

  • 4
    this approach (fetching on browser) is strongly discouraged, since you are exposing your credentials to the public; by the way the second snippet is the way to go and you must set CORS headers in your backend or use some sort of proxy or bypass it – Mechanic Jul 05 '23 at 18:42
  • As per the above comment, and the error: configure your server to allow fetch requests from the location(s) you're fetching from. _How_ you do that depends entirely on the server package you're using, but you'll have to put that information in your post before anyone can help with that (although there are a million answers on how to configure CORS for pretty much all common packages on SO already, so a search should get you that information, too) – Mike 'Pomax' Kamermans Jul 05 '23 at 18:50
  • The server needs to set the correct CORS headers for this to work from a browser. – Evert Jul 05 '23 at 18:54

0 Answers0