ESP32的POST请求返回301

时间:2018-11-05 16:24:36

标签: nginx post http-post esp32

我在树莓派上有一个NGINX服务器。我想将ESP32开发板上的JSON文件发送到NGINX Web服务器。

第一步,我遵循了本教程: https://techtutorialsx.com/2017/05/20/esp32-http-post-requests/

它给出了以下代码:

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

const char* ssid = "yourNetworkName";
const char* password =  "yourNetworkPassword";

void setup() {

  Serial.begin(115200);
  delay(4000);   //Delay needed before calling the WiFi.begin

  WiFi.begin(ssid, password); 

  while (WiFi.status() != WL_CONNECTED) { //Check for the connection
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;   

   http.begin("http://jsonplaceholder.typicode.com/posts");  //Specify destination for HTTP request
   http.addHeader("Content-Type", "text/plain");             //Specify content-type header

   int httpResponseCode = http.POST("POSTING from ESP32");   //Send the actual POST request

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

   }

   http.end();  //Free resources

 }else{

    Serial.println("Error in WiFi connection");   

 }

  delay(10000);  //Send a request every 10 seconds

}

如果在下面的行中使用此代码,没问题

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

我的ARDUINO IDE的串行监视器返回:

201
{
  "id": 101
}

但是,当我仅将前一行替换为

http.begin("http://82.145.56.62:151/postfile");

我在串行监视器上看到这个:

301
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3</center>
</body>
</html>

你能知道我的问题吗?

谢谢,

编辑

我又前进了一点。我已经在目录 posts 中创建了一个php文件。现在,我收到了HTTP代码200,因此我的网络服务器收到了POST请求。

新问题:我无法弄清楚如何在我的php文件中显示POST内容。你有个主意吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我通过替换解决了我的问题:

http.addHeader("Content-Type", "text/plain");

作者

http.addHeader("Content-Type", "application/x-www-form-urlencoded");