I was surprised by an experience with relative paths in Javascript today. I’ve boiled down the situation to the following:
Suppose you have a directory structure lik
This is not exactly a recommendation since it relies on a number of things that aren't guaranteed to work everywhere or to continue to work into the future, however it works for me in the places I need it to and it might help you.
const getRunningScript = () => {
return decodeURI(new Error().stack.match(/([^ \n\(@])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0])
}
fetch(getRunningScript() + "/../config.json")
.then(req => req.json())
.then(config => {
// code
})
When you say fetch('data.json')
you are effectively requesting http://yourdomain.com/data.json
since it is relative to the page your are making the request from. You should lead with forward slash, which will indicate that the path is relative to the domain root: fetch('/js/data.json')
. Or fully quality with your domain fetch('http://yourdomain.com/js/data.json')
.