在 Javascript 中使用 fetch 的相对路径 [英] Relative paths with fetch in Javascript

查看:30
本文介绍了在 Javascript 中使用 fetch 的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天对 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

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

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 加载 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.jsonapp.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

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

Is there an explanation for why this is the case?

推荐答案

当你说 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 中使用 fetch 的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆