Search code examples
javascriptamazon-web-servicescloud9-ideaws-cloud9

Failing to fetch my local API running in localhost (Amazon Cloud 9)


I have a simple flask server that returns a JSON (flask automatically do that when you return a python dict) when it receives a GET request to / endpoint.

Flask server

It's running on my 5000 port: Server is running on 5000 port

I know it's running and reachable as I managed to request to it, and receive a valid response, using curl, twice:

using curl

Both requests are logged into the server logs as well, on second print.

I'm trying to fetch to my server from a html/js script as:

const URL = "http://127.0.0.1:5000/"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))

or

const URL = "http://localhost:5000/"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))

But I get the same error twice:

1: GET http://localhost:5000/ net::ERR_CONNECTION_REFUSED

2: Uncaught (in promise) TypeError: Failed to fetch Errors

I know the code itself works because I managed to fetch Githubs API:

const URL = "https://api.github.com/users/nluizsoliveira"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))

Fetch github API

I'm not sure why I can't fetch to my localhost. I think it has something to do with how cloud9 deals with ports. When removing http://localhost from the url:

const URL = ":5000"
fetch( URL )
.then(response=>response.json())
.then(json=>console.log(json))

the snippet also fails, but it seems that the request is somehow appending the url to my C9 url.

Have someone faced that situation before? Thanks a lot in advance!

removing localhost from url


EDIT: Just to clarify, i'm not running that js/html (directly) on my browser tab. I'm running it on the C9's built in browser, which is available through "preview running application":

enter image description here


Solution

  • With AWS Cloud 9 Preview, AWS gives you a private link like https://12a34567b8cd9012345ef67abcd890e1.vfs.cloud9.us-east-2.amazonaws.com which gives you access to your application. To get that link click preview application and copy it from the browser tab.

    Use that link in your code instead of localhost. AWS Documentation:Preview a running application.