Javascript中的相对路径 [英] Relative paths with fetch in Javascript
问题描述
我对今天使用Java的相对路径感到惊讶.我将情况归结为以下几点:
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
我所有的app.html
都运行js/app.js
<!DOCTYPE html>
<title>app.html</title>
<body>
<script src=js/app.js></script>
</body>
app.js
加载JSON文件并将其粘贴在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)
数据是有效的JSON,只是一个字符串:
The data is valid JSON, just a string:
"Hello World"
这是fetch
的最小用法,但是令我惊讶的是,传递给fetch
的URL必须相对于app.html
而不是相对于app.js
.我希望这条路径可以正常工作,因为data.json
和app.js
在同一目录(js/
)中:
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
有这种情况的解释吗?
推荐答案
当您说fetch('data.json')
时,实际上是在请求http://yourdomain.com/data.json
,因为它与您提出请求的页面有关.您应以正斜杠开头,这将指示该路径相对于域根目录:fetch('/js/data.json')
.或完全符合您的域fetch('http://yourdomain.com/js/data.json')
.
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')
.
这篇关于Javascript中的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!