添加相对路径以获取请求

Ale*_*tin 2 fetch reactjs react-router create-react-app react-router-dom

我正在使用create-react-app和制作一个反应应用程序react-router-dom 4。我的问题是,当我加载默认“/”以外的 URL 时,相对路径会被添加到正在发出的请求中。

例如,如果我进入mysite.com/templatesurl 搜索栏,我的 fetch 请求会fetch("templates/item.json")请求 url:mysite.com/templates/templates/item.json但如果我从主页导航到/templates使用Linkreact-router-dom 中的 组件,则情况并非如此。

有什么方法可以避免在获取请求之前添加相对路径?

Ayu*_*hya 5

fetch如果您不以/绝对 url开头或指定绝对 url,则将加载相对于您打开的 url 的路径。

如果为了始终从 获取https://www.yourdomain.com/templates/item.json,您应该将获取请求修改为 ->fetch("/templates/item.json")

或者

指定绝对 url -> fetch("https://www.yourdomain.com/templates/item.json")