在 Javascript 中使用 fetch 的相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36369082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:58:19  来源:igfitidea点击:

Relative paths with fetch in Javascript

javascriptpathrelative-pathfetch-api

提问by j_ernst

I was surprised by an experience with relative paths in Javascript today. I've boiled down the situation to the following:

我今天对 Javascript 中的相对路径的体验感到惊讶。我将情况归结为以下几点:

Suppose you have a directory structure like:

假设您有一个目录结构,例如:

app/
   | 
   +--app.html
   +--js/
        |
        +--app.js
        +--data.json

All my app.htmldoes is run js/app.js

app.html所做的就是运行js/app.js

<!DOCTYPE html>
<title>app.html</title>
<body>
<script src=js/app.js></script>
</body>

app.jsloads the JSON file and sticks it at the beginning of body:

app.js加载 JSON 文件并将其粘贴在以下内容的开头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:

数据是有效的 JSON,只是一个字符串:

"Hello World"

This is a pretty minimal usage of fetch, but I am surprised that the URL that I pass to fetchhas to be relative to app.htmlinstead of relative to app.js. I would expect this path to work, since data.jsonand app.jsare in the same directory (js/):

这是一个相当小的使用fetch,但我感到奇怪的是,我传递给URLfetch必须是相对app.html而不是相对app.js。我希望这条路径可以工作,因为data.jsonapp.js位于同一目录 ( js/) 中:

fetch('data.json') // nope

Is there an explanation for why this is the case?

有没有解释为什么会这样?

回答by j_ernst

When you say fetch('data.json')you are effectively requesting http://yourdomain.com/data.jsonsince 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').

当您说fetch('data.json')您正在有效地请求时,http://yourdomain.com/data.json因为它与您发出请求的页面相关。您应该以正斜杠开头,这将表明该路径是相对于域根目录的:fetch('/js/data.json')。或者完全符合您的域的质量fetch('http://yourdomain.com/js/data.json')