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')
Is there any explanation why this is so?
user2467065
source share