簡體   English   中英

HTTPClient收到錯誤拒絕到節點JS服務器(奇怪的行為)

[英]HTTPClient getting error refused to node JS server (weird behaviour)

問題:運行ESP32腳本的第一分鍾〜, post請求產生HTTPC_ERROR_CONNECTION_REFUSED ,因此沒有數據到達服務器。 在第一分鍾之后,一些請求丟失了,但是大多數情況下,請求每隔2s到達服務器一次(應該如此)。

將數據發送到服務器的功能:

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();
}

節點JS服務器:

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);

如果我使用測試網站來接收不是我的服務器的POST請求,例如requestcatcher.com則不會丟失任何請求。 反之亦然,如果我使用網站發送POST請求(例如hurl.eu則我的服務器沒有任何問題。

這是ESP32發送的發布請求:

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

嘗試使用JSON發送數據,您可以使用ArduinoJson庫。

然后在loop()方法中使用類似這樣的代碼。

  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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM