Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch API not working with localhost/127.0.0.1

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.

like image 543
Andy Avatar asked May 27 '17 13:05

Andy


People also ask

Can you use fetch on localhost?

here is an example of a regular fetch request to localhost:3000/api. <=== (test server). So, in order to make the fetch you have to find the local ip adress of your computer and replace it with localhost.

How do you fetch data from localhost API in react?

Step to run the application: Open the terminal and type the following command. Output: Now open localhost:300 and in the console, the data is fetched. 3. Async-Await: This is the preferred way of fetching the data from an API.

How do I run fetch API?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.


2 Answers

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.

like image 152
Ankan Avatar answered Sep 17 '22 14:09

Ankan


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

like image 27
KevinZhou Avatar answered Sep 18 '22 14:09

KevinZhou