breakfastea
breakfastea

Reputation: 15

Cannot connect to http python server from node-red

Context

I've defined an http server with a python script, this server is used to then make GET calls from NODE-RED and thus obtain information present on a configuration JSON file. The python server and the node-red instance are running on the same localhost (my computer) but with different ports. Here it is the code of the http python server:

from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class MyRequestHandler(BaseHTTPRequestHandler):
    
    def do_GET(self):
        if self.path == '/configuration':
            try:
                with open('cfg.json', 'r') as f:
                    json_data = json.load(f)
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps(json_data).encode('utf-8'))
                
            except FileNotFoundError:
                self.send_response(404)
                self.end_headers()
                self.wfile.write(b"File not found")
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b"404 Not Found")

server_address = ('', 8000)
httpd = HTTPServer(server_address, MyRequestHandler)

print("Starting server on port 8000...")
httpd.serve_forever()

#Problem

When I try to connect via node-red to make the GET call to http://localhost:8000/configuration via an http request node this gives the error code: **"RequestError: connect ECONNREFUSED 127.0.0.1:8000" **

I tried using different ports for the python server but the result is still the same, also I saw that the macOS firewall is disabled. I am able to connect to the server via browser or postman by making the GET call and display the message, I only encounter the problem on NODE-RED and do not understand how to solve it.

Here it is the JSON message (which is not a problem, since I view it perfectly on browsers and postman):

{
  "poll-interval": {
    "value": 15,
    "uom": "seconds",
    "description": "Polling interval"
  },
  "uom": "celsius",
  "precision": "high"
}

Upvotes: 0

Views: 67

Answers (1)

hardillb
hardillb

Reputation: 59751

This will probably be an IPv6 problem, localhost will resolve to both 127.0.0.1 and ::1 and recent versions of NodeJS will use which ever the underlying OS returns first.

The following answer will let the HTTPServer bind to :: (which is the IPv6 version 0.0.0.0) and this should make the server listen on both IPv4 and IPv6

https://stackoverflow.com/a/55976197/504554

Upvotes: 0

Related Questions