Why do I get a -1 HTTP POST Response Code only when I want to send the request to my local PHP-script?

386 views Asked by At

I want my ESP32 to write data via an HTTP POST Request to my local database. For this I downloaded XAMPP and wrote a PHP script that inserts the data into the database. Moreover I have ESP32 Code that connects to WiFi and should send an HTTP POST Request by sending the data to the PHP script. I am facing the error code -1 every time I try to send the request to my local PHP script. However, when I send the request to for example http://arduinojson.org/example.json the httpResponseCode is not equal -1 (httpResponseCode = 403 -> forbidden access).

ESP32 Code:

#include <WiFi.h>
#include <HTTPClient.h>

#include <Wire.h>

//network credentials
const char* ssid     = "[My_WIFI_SSID]";
const char* password = "[My_WIFI_PASSWORD]";

//Domain name and URL path or IP address with path
const char* serverName = "http://[My_IP_ADDRESS]/insert_temp-post.php";
//using http://arduinojson.org/example.json instead -> httpResponseCode != -1

// Keep this API Key value to be compatible with the PHP code provided in the project page. 
// If you change the apiKeyValue value, the PHP file also needs to have the same key 
String apiKeyValue = "tPmAT5Ab3j7F9";

void setup() {
  Serial.begin(9600);
  
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  //Check WiFi connection status
  if(WiFi.status()== WL_CONNECTED){
    WiFiClient client;
    HTTPClient http;
    
    // Domain name with URL path or IP address with path
    http.begin(client, serverName);
    
    //content-type header specification
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    
    // Prepare HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&temperature=34.5";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);

    // Send HTTP POST request
    int httpResponseCode = http.POST(httpRequestData);
        
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    // Free resources
    http.end();
  }
  else {
    Serial.println("WiFi Disconnected");
  }
  //Send an HTTP POST request every 30 seconds
  delay(30000);  
}

Do you have an idea, what might cause this error code? Until now I only found out that you should use your PCs IP-address instead of "localhost" in the servers URL. I hoped that it would fix my problem, but obviously that is not the right solution in my case.

0

There are 0 answers