How to solve for: net::ERR_CONNECTION_REFUSED when GET data to React?

andres picture andres · Jan 4, 2021 · Viewed 9.4k times · Source

I'm trying to get this API call to work using axios:

const getData = () => {
    Axios.get("http://localhost:3000/security?select=symbol,company",
    {headers: {Authorization: 'Bearer 73Ntx3b6SwNXC7ANV3tw4wFfDdKntB26',
                "Access-Control-Allow-Origin": "*",
                mode: "cors",               
    }}
    ).then((response) => {
        console.log(response)
    })
}

My local API server is up and running, I can make requests using curl and see JSON data. However, the calls do not work when I implement a GET request in my React App.

I'm a little curious to know why I'm getting these errors:

Failed to load resource: net::ERR_CONNECTION_REFUSED
createError.js:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:84)
createError @ createError.js:16
handleError @ xhr.js:84

Something is blocking the API from showing the data, I assume it's React. In my stack, this connection to localhost:3000 API is only used once in the code above, it simply retrieves unique data...

Any ideas on how to solve?

EDIT: I have added a picture to show that the port is up and my API is up enter image description here

EDIT EDIT: So I tested my API live in production to see if it was a backend issue, I can access my API live from a real web-address. No issue there. I guess I tinkered my backend closer to getting the API request to work with React, because now I'm getting an 401 unauthorized Request instead of my previous error.

Here is the config file for my nginx backend for my api url:

    location /data/ {
      default_type  application/json;
      proxy_hide_header Content-Location;
      add_header Content-Location  /data/$upstream_http_content_location;
      add_header Access-Control-Allow-Origin *;
      proxy_set_header  Connection "";
      proxy_http_version 1.1;
      proxy_pass http://localhost:3000/;
        }
}

I have also added new code for my REACT get request above.

Answer

Gurgen Sargsyan picture Gurgen Sargsyan · Jan 4, 2021

Try to set Axios baseURL: 'http://localhost:3000' and add option mode: "cors"