0
votes

I have a node.js express server hosting my API on port 7070. I have a Flask server hosting my webpage on port 5000. I can access my API from the server using curl with curl http://localhost:7070/latest and the API returns the result successfully. On my webserver I am trying to call the API using getJSON however it only works when I replace localhost with the server local IP.

If I try to access my API using localhost with http://127.0.0.1:7070/latest, or http://localhost:7070/latest create a net::ERR_CONNECTION_REFUSED an error is thrown in chrome.

If I change localhost to my local IP 192.168.68.72 for http://192.168.68.72:7070/latest it works correctly. I need to use localhost as my application is self-hosted so the URL can't be hard linked.

What am I doing wrong here, I have searched previous issues and have checked that the port is open with netstat -tnlp

enter image description here

Is there some other way I need to say connect to the same server but on a different port instead of localhost?

Thanks

1
getJSON sounds like jQuery? Which means you're requesting the API from inside your browser, which means localhost refers to the computer running your browser, i.e. the machine you're sitting in front of, not the Pi. One way to solve this is to make API requests via your flask server, for instance by using a route like /api/latest and have flask forward /api requests to the 7070 server. - Chris G
@ChrisG Yeah getJSON is jQuery, I thought that might be the case I will look at doing it through Flask, do you have any links for this or any alternative approaches? - Luke Prior
"//" + location.host + ":7070/latest" should also work - Chris G
@ChrisG that tries to go to http//192.168.68.72:5000:7070/latest, how do I get rid of the :5000 port of the webserver? - Luke Prior
location.host.split(':')[0] should do it - Chris G

1 Answers

0
votes

Thanks to Chris I realised that localhost was looking at my own PC and not the server PC.

To fix this I used "//" + location.hostname + ":7070/latest" instead of http://localhost:7070/latest and it worked perfectly.