Problem: For the first-minute ~ of running the ESP32 script the post
request produces HTTPC_ERROR_CONNECTION_REFUSED
and therefore no data gets to the server. After the first minute, a few requests get lost but for the most part requests reach the server every 2s~ (as it should).
Function to send data to the server:
void sendPostData(String data) {
// Send the post data to the server
http.begin(SERVER_IP); // Begin the HTTP connection
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpResponseCode = http.POST("val=" + data);
http.writeToStream(&Serial);
http.end();
}
Node JS server:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', function (req, res) {
console.log(req.body);
res.end();
});
app.listen(80);
If I use a test website to receive POST requests that isn't my server, eg, requestcatcher.com
then no requests are lost. And vice versa, if I use a website to send POST requests such as hurl.eu
then my server doesn't have any issues.
This is the post request the ESP32 is sending out:
POST / HTTP/1.0
Host: sadasdasd.requestcatcher.com
Connection: close
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0
Connection: close
Content-Length: 10
Content-Type: application/x-www-form-urlencoded
User-Agent: ESP32HTTPClient
Try to send data with JSON, You can use ArduinoJson
Library for it.
then use code like this in the loop()
method.
StaticJsonBuffer<300> JSONbuffer; //Declaring static JSON buffer
JsonObject& JSONencoder = JSONbuffer.createObject();
JSONencoder["val"] = data;
char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
HTTPClient http; //Declare object of class HTTPClient
http.begin(SERVER_IP); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int httpCode = http.POST(JSONmessageBuffer); //Send the request
String payload = http.getString();
http.end();
delay(1000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.