Relative paths with fetch in Javascript
Asked Answered
M

3

63

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 like:

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

All my app.html does is run js/app.js

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

app.js loads the JSON file and sticks it at the beginning of 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 string:

"Hello World"

This is a pretty minimal usage of fetch, but I am surprised that the URL that I pass to fetch has to be relative to app.html instead of relative to app.js. I would expect this path to work, since data.json and app.js are in the same directory (js/):

fetch('data.json') // nope

Is there an explanation for why this is the case?

Merciful answered 2/4, 2016 at 4:8 Comment(4)
JS can come from places whose folders can't be pointed to due to SOP, so it's always been page-relative.Brisbane
Note that this doesn't really have much to do with JavaScript; it's the way that web browsers interpret paths in HTTP requests. The main page defines the URL context for everything: script references, images, stylesheets, and XHRs.Lockwood
Hi, for what it’s worth CSS paths don’t work this way, they’re relative to the source directory of the stylesheet — if you have, say, body { background-image: url(pic.gif) } in css/styles.css, then the browser will look for pic.gif in css/, not /. That’s the behavior I would expect with JS, but apparently it’s not true.Merciful
if you are using ESModules: fetch(import.meta.resolve("./data.json"))" if you are using CommonJS ("require" package from npm): fetch(require.resolve("./data.json"))Victualer
L
91

When you say fetch('data.json') you are effectively requesting http://yourdomain.com/data.json since it is relative to the page you're 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 qualify with your domain fetch('http://yourdomain.com/js/data.json').

Losing answered 2/4, 2016 at 5:27 Comment(3)
Is this just domain or really origin, which is FQDN along with the HTTP port being used such as yourdomain.com:8080/data.json ?Manage
Seems as Chrome does no more fetch same directory without a serverArtois
Behavior in Chrome is that it's always taken to be relative to the root, even when that's undersired.Dilorenzo
B
11

An easy way to understand why it must be the case is to consider what should happen if we write a helper function in app/js/helper/logfetch.js:

// app/js/helper/logfetch.js
function logFetch(resource) {
    console.log('Fetching', resource);
    return fetch(resource);
}

Now, consider what happens if we use logFetch from app/js/app.js:

// app/js/app.js
fetch('data.json');    // if this is relative to js/, then ...
logFetch('data.json'); // should this be relative to js/ or js/helper/?

We might want these two calls to return the same thing - but if fetch is relative to the contained file, then logFetch would request js/helper/data.json instead of something consistent with fetch.

If fetch could sense where it is called from, then to implement helper libraries such as logFetch, the JavaScript would need a whole range of new caller-location-aware functionality.

In contrast, performing the fetch relative to the HTML file provides more consistency.

CSS works differently because it doesn't have the complexity of method calling: you can't create "helper CSS modules" that transform other CSS modules, so the idea of relative paths is a lot more conceptually cleaner.

Bleeder answered 21/1, 2021 at 23:1 Comment(1)
This should be the accepted answer. The OP asked for an "an explanation for why this is the case" and this is the answer that really explains the "why".Felsite
A
3

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
  })
Adaline answered 2/7, 2020 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.