Hi all, I'm trying to get my arduino to post some code to my node.js server. I'm using the enc28j60 ethernet card and an arduino uno. I can successfully connect to the internet via the ethernet card and I can send a get request to google, but when I try and post to my server the arduino starts sending back malformed data to the serial monitor and my server never receives the post request. I've scoured other posts here about similar problems but none of those solutions seemed to work. Does anyone know what I'm doing wrong?
#include <ArduinoJson.h>
#include <ArduinoJson.hpp>
#include <ArduinoHttpClient.h>
#include <EthernetENC.h>
#include "arduino_secrets.h"
//WiFiMulti wifiMulti;
//ip address and mac address
byte ip [] = SECRET_IPADDRESS;
byte mac [] = { 0x74,0x69,0x69,0x2D,0x30,0x32 };
byte server [] = SECRET_SERVERADDRESS;
int port = 3000;
//create ethernet client instance
EthernetClient etherClient;
// HttpClient client;
HttpClient client = HttpClient(etherClient,server,port);
void setup() {
// start the Ethernet connection:
Ethernet.begin(mac);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
//check if ethernet cable is connected
while (Ethernet.linkStatus() == LinkOFF) {
// Ethernet.maintain();
Serial.println("Ethernet cable is not connected.");
Serial.println("trying again.");
Ethernet.maintain();
delay(500);
}
Serial.print("IP = ");
Serial.println(Ethernet.localIP());
postData();
}
void loop() {
}
void postData(){
Serial.println("Making a POST request");
//prepare the data to be sent
String contentType = "application/json";
StaticJsonDocument<200> doc;
doc["Test"] = "success";
String requestBody;
serializeJson(doc,requestBody);
//send the data
client.beginRequest();
client.post("/update");
client.sendHeader("Content-Type",contentType);
client.sendHeader("Content-length", requestBody.length());
client.sendHeader("X-Custom-Header", "custom-header-value");
client.beginBody();
client.print(requestBody);
client.endRequest();
//read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Status code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);
}`