Fetch returns html source of the my own index.html

穿精又带淫゛_ 提交于 2020-02-24 09:22:11

问题


I am trying to use fetch in an react-create-app server(localhost:3000) to get a static .json file from my apache(localhost:80) but it returns source of my react index.html file!

Specifying port number results in "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())});

回答1:


Downright the problem comes to making react-create-app work with a local server which is explained in this guide https://daveceddia.com/create-react-app-express-backend/

In short I needed to put a proxy property with the value equal to address of my local server in my package.json. In my case:

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



回答2:


Try a fully qualified 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())});

Note the http://




回答3:


In my situation, I was calling fetch("/path/to/some/api") and getting this result. The problem was that fetch by default does not send authentication info in the request (in my case users are authenticated by a session cookie), and my API was rejecting the request and for some reason issuing a redirect to /.

The solution:

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

Also, what helped me debug the problem:

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

With the above, server calls which resulted in redirects were rejected.



来源:https://stackoverflow.com/questions/44852313/fetch-returns-html-source-of-the-my-own-index-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!