Fetch API not working with localhost/127.0.0.1

为君一笑 提交于 2020-05-25 07:43:05

问题


Just as background, I have a react app sitting on a remote EC2 Ubuntu instance. The same server also runs a Go app listening on port 8080 (port has been opened to everyone from the Security settings).

I am trying to make a request with Fetch API, from the React app, as follows:

var bearer = 'Bearer ...'
return fetch('http://localhost:8080/home', {
  headers: new Headers({
    'Authorization': bearer
  })
})

In the console, from both Chrome and Firefox, I am getting:

TypeError: NetworkError when attempting to fetch resource

The same goes when I substitute localhost with 127.0.0.1.

Using the external IP of the EC2 instance, however, works (and triggers a CORS request - due to the 'Authorization' header - which is handled smoothly by the server).

In the latter case, I can also see the server logging the incoming request for both OPTIONS and GET (in the former case, no logs are present for either method).

I also tried CURL'ing from the EC2 machine to localhost and the request effectively goes through which leads me to think that with the Fetch API the request is not triggered at all.

Any advice would be appreciated. If I am doing anything wrong please point me in the right direction.


回答1:


When you write localhost it calls your (localhost) machine (on which the browser is present) because the js code is running in your browser.

You should create a domain/sub-domain for your API endpoint and use it instead of localhost or continue to use the hard-coded IP address.

You should also allow only your frontend website domain in the allowed origins for your backend. Ex. your website can be www.example.com and backend url can be www.api.example.com. You should allow only www.example.com as the origin which can be served through www.api.example.com. You will need to configure this in the backend.




回答2:


I just had the same problem. I managed to get this working by adding "proxy": "http://localhost:4000" to package.json.

Then you can write requests like fetch('/api/todos').

They explain it good here.




回答3:


If you're trying to send a request to localhost, and you are hosting your server on localhost, then you don't need to specify the url, you only need to tell fetch() your path.

For example, my api end point is http://localhost:8082/api/config, then i would do fetch('/api/config').

Here is a link to fetch method, link



来源:https://stackoverflow.com/questions/44217376/fetch-api-not-working-with-localhost-127-0-0-1

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