Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

Relative paths with fetch in Javascript

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...