[SOLVED] Relative links work on locahost:3000 but not on GitHub Pages

[SOLVED] Relative links work on locahost:3000 but not on GitHub Pages
0

#1

My root relative links work when I’m developing locally, but not on my GitHub Pages project site.

This is my directory structure
| - data
|      | - data.json
| - js
|      | - script.js
| - index.html

When I’m developing locally, I can successfully get data from data.json by using the fetch API.
However, my fetch request fails when I deploy my site on GitHub Pages.
This is because it is assumed by the browser that my site lives at username.github.io, when it is in fact in username.github.io/REPO.
So when I do fetch('/data/data.json'), the browser interprets that as a GET request to username.github.io/data/data.json, instead of username.github.io/REPO/data/data.json.

I could change my URL so that it would include my repo like so:
fetch('/REPO/data/data.json');
But then fetch wouldn’t work when I develop locally.

And apparently you can’t use file relative paths as the URL in the fetch method.

So how do I access my data both locally and on GitHub Pages without using absolute URLs?

I have googled and come to a lot of dead ends. The only idea I have is to create a script that would create a build folder and replace script.js with a new script.js file that will have switched / links to /REPO/ links. But this is beyond the scope of my ability or knowledge :sweat_smile: Like how can I replace text in a javascript file and create a new file with the replaced text? I have a little experience with gulp, but none with node. Or maybe there is an npm package for this? I feel like a lot of people would have this problem.

EDIT: The problem was that I was using relative links incorrectly. The URL inside the fetch method should have been relative to index.html, not to script.js. So the solution is fetch('data/data.json').


#2

When i look in the sources tab i don’t see a data folder.
I kinda gave up on github pages once i found netlify, you should check them out.


#3

That’s a very interesting observation :thinking: It’s weird because there’s definitely a data folder in GitHub.

I have figured out how to get around this issue (I was using relative links incorrectly), but thank you very much for your suggestion.