Relative paths with fetch in Javascript

前端 未结 2 919
一生所求
一生所求 2020-12-03 03:00

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

相关标签:
2条回答
  • 2020-12-03 03:10

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

    0 讨论(0)
  • 2020-12-03 03:22

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

    0 讨论(0)
提交回复
热议问题