1

I've looked around for solutions and tried but can't get this to work. I'm trying to send a POST request to a localapi. My code:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include "ArduinoJson.h"
#include <WiFiClient.h> 

const char* ssid = "VIOT"; 
const char* password = "********";
const char* sensor_0 = "1234";
const char* sensor_1 = "5678";
const char* sensor_2 = "3678";
String postMessage;

void setup()

 { 
Serial.begin(115200);   
WiFi.begin(ssid, password); 

while (WiFi.status() != WL_CONNECTED) 
{
delay(1000); 
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi"); 
Serial.println(WiFi.localIP());
}

void loop()
{ 
  WiFiClient client;
  HTTPClient http;
  StaticJsonDocument<256> doc;  
  doc["batteryCharge"] = sensor_0;
  doc["powerUsage"] = sensor_1;
  doc["powerProduced"] = sensor_2;
  
  serializeJson(doc, postMessage);

  Serial.print("[HTTP] begin...\n");
  http.begin(client,"http://192.168.1.190/",3000); 
  http.addHeader("Content-Type", "application/json"); 
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(postMessage); 
  Serial.print(httpCode);
  if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString(); 
      Serial.println("HTTP POST request successful"); 
      Serial.println("Response: " + payload); 
} 
} 

else {

 Serial.println("HTTP POST request failed");

 } 

http.end(); delay(10000); // Wait for 10 seconds before sending the next request

 }

Both devices are connected to the same network and my computer ip is 192.168.1.190. Tested my api on postman and it ran successfully. Here is the error:

15:45:26.469 -> Connecting to WiFi...
15:45:27.469 -> Connecting to WiFi...
15:45:29.207 -> Connecting to WiFi...
15:45:30.208 -> Connecting to WiFi...
15:45:30.208 -> Connected to WiFi
15:45:30.208 -> 192.168.1.180
15:45:30.208 -> [HTTP] begin...
15:45:30.208 -> [HTTP] POST...
15:45:30.208 -> -1HTTP POST request failed
1
  • 1
    localhost ... is a synonym for 127.0.0.1 ... it is an IP that does not exist on any network ... it exists only within the device where the program is referring to it
    – jsotola
    Aug 1 at 14:56

1 Answer 1

0

I found the problem. I changed

http.begin(client,"http://192.168.1.190/",3000); 

to

http.begin(client,"http://192.168.1.190:3000"); 
1
  • and why did you have http.begin(client,"http://192.168.1.190/",3000);?
    – Juraj
    Aug 1 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.