toit

Toit - How can I connect to `localhost` using `http.Client`?


I am trying to test Toit on an ESP32 on my local network. I have a fastapi app running on my laptop and I'm trying to run a GET request.

I am using the http package:

$ toit pkg install github.com/toitlang/pkg-http

My Code main.py:

import http
import net
import encoding.json

URL ::= "localhost:8000"
PATH ::= "/"

main:
  network := net.open
  client := http.Client network
  // The `get` method automatically closes the connection when
  // the response has been fully read.
  response := client.get URL PATH
  data := json.decode_stream response.body

  print data

But I am getting the error: Connection refused

$ toit run --device <UUID> main.toit
2022-05-30T20:47:00.111752Z: <process initiated>
2022-05-30T20:47:00.384733Z: <stack trace>
EXCEPTION error.
Connection refused
  0: TcpSocket.connect         system/modules/tcp.toit:149:40
  1: TcpSocket.connect         system/modules/tcp.toit:139:12
  2: WifiNetworkInterface.tcp_connect system/components/wifi.toit:101:7
  3: NetworkInterfaceResource.tcp_connect system/components/network.toit:95:26
  4: register_network.<lambda> system/components/network.toit:26:23
  5: KernelBroker.register_descriptor_procedure.<lambda> system/kernel/rpc.toit:44:14
  6: RpcRequest_.process.<block> <sdk>/rpc/broker.toit:98:26
  7: RpcRequest_.process       <sdk>/rpc/broker.toit:95:3
  8: RpcRequestQueue_.ensure_processing_task_.<lambda>.<block>.<block> <sdk>/rpc/broker.toit:214:20
  9: RpcRequestQueue_.ensure_processing_task_.<lambda>.<block> <sdk>/rpc/broker.toit:209:9
 10: RpcRequestQueue_.ensure_processing_task_.<lambda> <sdk>/rpc/broker.toit:204:56



2022-05-30T20:47:00.518790Z: <process terminated - exit code: 1>

I get the same result whether I use localhost:8000 or 127.0.0.1:8000.


I am able to hit the endpoint on my laptop with a simple cURL command, so the endpoint is working.


Solution

  • The toit run command executes the application on the ESP32. As such, the localhost then refers to the device itself and not your machine.

    You can either try to run the Toit program locally on your machine (using the open-source version of Toit: https://github.com/toitlang/toit/releases), or you can change the localhost to the IP address of your machine.

    How you get the IP address of your local machine depends on your operating system. On my Linux machine I would just type ip address.