0

我的目标是将数据发布到 Flask 服务器。为此,我在计算机(Jupyter)上运行以下代码:

from flask import Flask
    
    from flask import request
    
    app = Flask(__name__)
    
    @app.route('/postjson', methods = ['POST'])
    
    def postJsonHandler():
    
        print (request.is_json)
    
        content = request.get_json()
    
        print (content)
    
        return 'JSON posted'
    
      
    
    app.run(host='0.0.0.0', port= 8090)

在 esp 上,我有以下功能负责发布,现在它只是用于测试,稍后我将进一步完善该功能。

//Posts data to server
void post_to_server(String url)
{
  HTTPClient http;

  // Prepare JSON document
  JsonObject root = doc.to<JsonObject>();
  JsonArray pressure = root.createNestedArray("pressure");
  JsonArray time = root.createNestedArray("time");

  pressure.add("Pressure");
  time.add("Time");

  // Serialize JSON document
  String json;
  serializeJson(root, json);

  // Send request
  http.begin(url);
  http.addHeader("Content-Type", "application/json");

  int httpResponseCode = http.POST(json); //Send the actual POST request

  // Read response
  Serial.print(http.getString());

  if (httpResponseCode > 0)
  {
    String response = http.getString(); //Get the response to the request
    Serial.println(httpResponseCode);   //Print return code
    Serial.println(response);           //Print request answer
  }
  else
  {
    Serial.print("Error on sending POST: ");
    Serial.println(httpResponseCode);

    // Disconnect
    http.end();
  }
}

所以这是奇怪的事情,当我像这样在测试服务器上调用函数时:

  post_to_server("http://jsonplaceholder.typicode.com/posts");

它有效,我在串行监视器上得到了预期的以下响应:

 {
  "pressure": [
    "Pressure" 
  ],
  "time": [
    "Time"
  ],
  "id": 101

但是当我尝试像这样发布到我的 PC 上运行的服务器时:

 post_to_server("http://127.0.0.1:8090/postjson");

我收到以下错误:

0
[E][WiFiClient.cpp:258] connect(): socket error on fd 54, errno: 104, "Connection reset by peer"
Error on sending POST: -1

我无法真正理解这一点,所以我来到了这里。我会给予任何帮助。在 Postman 上测试时,我还得到以下信息:

在此处输入图像描述

4

1 回答 1

2
post_to_server("http://127.0.0.1:8090/postjson");

这将永远无法在您的 ESP32 上运行。

127.0.0.1 是“环回地址” - 与 name 相同localhost。它是“这台电脑”的简写。

当您将它与在 Windows 机器上运行的程序一起使用时,该程序将尝试连接到 Windows 机器。

当您将它与 ESP32 一起使用时,这意味着连接到 ESP32。

您需要使用与您的 Windows 机器的网络连接相关的 IP 地址,无论是以太网还是 WiFi。127.0.0.1不管用。

于 2021-08-09T19:33:56.563 回答