获取我自己的 returns html 来源 index.html

Fetch returns html source of the my own index.html

我正在尝试在 react-create-app 服务器 (localhost:3000) 中使用 fetch 从我的 apache(localhost:80) 获取静态 .json 文件,但它 returns我的 React index.html 文件的来源!

指定端口号导致 "networking error"

const that=this;
fetch("localhost/myapp/data/structure.json").then((res)=> {return res.text()})
                .then(((data)=>{that.setState({structure: data})})).catch((e)=>{alert(e.toString())});

试试完全合格的 URL:

const that=this;
fetch("http://localhost/myapp/data/structure.json").then((res)=> {return res.text()})
                .then(((data)=>{that.setState({structure: data})})).catch((e)=>{alert(e.toString())});

注意 http://

问题完全在于使 react-create-app 与本指南中解释的本地服务器一起工作 https://daveceddia.com/create-react-app-express-backend/

简而言之,我需要在 package.json 中放置一个代理 属性,其值等于我本地服务器的地址。就我而言:

  "proxy": "http://localhost:80"

在我的情况下,我正在调用 fetch("/path/to/some/api") 并得到这个结果。问题是 fetch 默认情况下不会在请求中发送身份验证信息(在我的情况下,用户通过会话 cookie 进行身份验证),并且我的 API 拒绝请求并出于某种原因发出重定向至 /.

解决方法:

window.fetch("/path/to/some/api", { credentials: true });

此外,是什么帮助我调试了问题:

window.fetch("/path/to/some/api", { redirect: "error" });

通过上述,导致重定向的服务器调用被拒绝。