Relative Javascript Extract Paths

I was surprised at the experience with relative paths in Javascript today. Ive reduced the situation to the following:

Suppose you have a directory structure, for example:

app/ | +--app.html +--js/ | +--app.js +--data.json 

Running all my app.html js/app.js

 <!DOCTYPE html> <title>app.html</title> <body> <script src=js/app.js></script> </body> 

app.js loads the JSON file and inserts it at the beginning of the body :

 // js/app.js fetch('js/data.json') // <-- this path surprises me .then(response => response.json()) .then(data => app.data = data) 

The data is valid JSON, just a line:

 "Hello World" 

This is a pretty minimal use of fetch , but I'm surprised that the URL I pass to fetch should refer to app.html instead of relative app.js I expect this path to work, since data.json and app.js are in the same directory ( js/ ):

 fetch('data.json') // nope 

Is there any explanation why this is so?

+18
source share
1 answer

When you say fetch('data.json') , you are really asking for http://yourdomain.com/data.json , since it refers to the page you're making a request to. You must lead with a slash that indicates that the path refers to the domain root: fetch('/js/data.json') . Or all the quality with your fetch('http://yourdomain.com/js/data.json') domain fetch('http://yourdomain.com/js/data.json') .

+26
source

All Articles