3

I am making a react app using create-react-app and react-router-dom 4. My issue is, when I load a URL other than the default "/", the relative path gets prepended to requests being made.

For instance if I enter mysite.com/templates into the url searchbar, my fetch request fetch("templates/item.json") requests the url: mysite.com/templates/templates/item.json but if I navigate from the homepage to to /templates using the Link component from react-router-dom this isn't the case.

Is there any way to avoid the relative path being prepended to the fetch request?

AlexVestin
  • 2,548
  • 2
  • 16
  • 20

1 Answers1

6

fetch will load the path relative to the url you have opened if you don't begin with / or specify absolute url.

If order to fetch always from https://www.yourdomain.com/templates/item.json, you should modify your fetch request to -> fetch("/templates/item.json")

or

specify the absolute url -> fetch("https://www.yourdomain.com/templates/item.json")

Ayushya
  • 1,862
  • 1
  • 10
  • 15