Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative paths with fetch in Javascript

People also ask

What is a relative path JavaScript?

A link that has an absolute path will tell the computer which server to go to and then all the folders that you have to drill down through to get to the target. A link that has a relative path will be written to tell the computer how to get from the folder with the currently viewed topic to the target.

Can we use fetch in JavaScript?

JavaScript | fetch() Method. The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.

How fetch data fetch in JavaScript?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

How do you reference a relative path?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory.


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').


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
  })

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.