Home > Back-end >  How do I fetch relative to a JavaScript file
How do I fetch relative to a JavaScript file

Time:08-24

I have a file tree:

index.html

  | js
  |
  | data.json
  | script.js

index.html is just script.js

script.js:

(async function() {
  var req = await fetch("data.json");
  var json = await req.json();
  ...
})();

I'm trying to access data.json from script.js (js folder) instead of index.html.

So I can't just use js/script.js

How would I do this?

CodePudding user response:

Apparently you can get a path to the currently running script (if it's not ESM), using document.currentScript

Untested, but this would suggest you can build the path like this:

const dataUrl = new URL('data.json', document.currentScript.src);
const req = await fetch(dataUrl);
// etc

CodePudding user response:

Even though the data.json is in the same folder as script.js, since both these files are inside the js folder relative to index.html you would have to use

  var req = await fetch("js/data.json");
  • Related