ESP8266 HTTP post request return -1 http code

I am currently working on ESP8266. I tried to post my data using ESP8266 to my laravel website. I've been trying using postman and my API it is working. But, when I try to post from ESP8266 it is keep show that http code is -1 not 200 (success). This is my code,

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
 
void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin("ssid", "pass");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
  }
  Serial.print("Connected");
}
 
void loop() {
  int dummy = 100;

  WiFiClient wifiClient;
  HTTPClient http;

  //String json = "{\"device\":\"device_1\",\"suhu_lingkungan\":\"" + String(dummy) + "\",\"kelembaban_lingkungan\":\"" + String(dummy) + "\",\"kelembaban_tanah\":\"" + String(dummy) + "\"}";
  String formData = "device=device_1&suhu_lingkungan=" + String(dummy) + "&kelembaban_lingkungan=" + String(dummy) + "&kelembaban_tanah=" + String(dummy);

  http.begin(wifiClient, "http://127.0.0.1:8000/api/data");

  http.addHeader("Content-Type", "application/x-www-form-urlencoded");

  int httpCode = http.POST(formData);
  Serial.println(httpCode);
  String response = http.getString();
  Serial.println(response);
  http.end();
  delay(5000);
}
I am trying to change my ESP8266 device, change my WiFi, and trying to send dummy data. But, its still not working. Any solution? Thanks!

If the returning value is -1 it means "HTTPC_ERROR_CONNECTION_FAILED" (check ESP8266HTTPClient.cpp and ESP8266HTTPClient.h).
You should check what http.begin() returns, if "false" either your server is not active or not reachable. Check also WiFi.status() before trying to connect, just in case the network has been disconnected.

1 Like

Shouldn't your esp32 be the server and your webpage the client ? The the client will request
the data and the esp32 will respond to the request ?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.