2016-06-17 8 views
2

私はnodejs/expressjsバックエンドサービスを持っており、エンドポイントを使用してデバイスを登録したいと考えています。私はいくつかのJSONエンコードされたデータで私のサーバーにPOST要求を送る必要があります。私はこれをやるのに困っている。私は正常にGET要求を送信することができますし、私はサーバーから応答を取得しますが、私はPOST要求を送信しようとすると私は応答を取得しません。ここで私はそれを行う方法は次のとおりです。ESP8266WiFiライブラリを使用したHTTP POST要求の送信

//Make a post request 
void postRequest(const char* url, const char* host, String data){ 
    if(client.connect(host, PORT)){ 
    client.print(String("POST ") + url + " HTTP/1.1\r\n" + 
       "Host: " + host + "\r\n" + 
       //"Connection: close\r\n" + 
       "Content-Type: application/json\r\n" + 
       "Content-Length: " + data.length() + "\r\n" + 
       data + "\n"); 
    //Delay 
    delay(10); 

    // Read all the lines of the reply from server and print them to Serial 
    CONSOLE.println("Response: \n"); 
    while(client.available()){ 
     String line = client.readStringUntil('\r'); 
     CONSOLE.print(line); 
    } 
    }else{ 
    CONSOLE.println("Connection to backend failed."); 
    return; 
    } 
} 

答えて

6

リクエストがほとんど正しいです。 HTTP Message Specは、あなたが持っているすべてのヘッダーの終わりにCR + LFのペアが必要であることを示し、そしてボディスタートを示すために、しか含まない空白行がCR + LFのペアを持っています。

あなたのコードは、サーバーが10ミリ秒で応答しないこととして、私は、少し遅れを修正するだろう、

client.print(String("POST ") + url + " HTTP/1.1\r\n" + 
       "Host: " + host + "\r\n" + 
       //"Connection: close\r\n" + 
       "Content-Type: application/json\r\n" + 
       "Content-Length: " + data.length() + "\r\n" + 
       "\r\n" + // This is the extra CR+LF pair to signify the start of a body 
       data + "\n"); 

また、余分なペアを次のようになります。そうでなければ、コードは決してレスポンスを出力せず、失われます。あなたはArduinoのESP8266環境を使用している場合、彼らは HTTPを持って、それがさらに応答に

int waitcount = 0; 
while (!client.available() && waitcount++ < MAX_WAIT_COUNT) { 
    delay(10); 
} 

// Read all the lines of the reply from server and print them to Serial 
CONSOLE.println("Response: \n"); 
while(client.available()){ 
    String line = client.readStringUntil('\r'); 
    CONSOLE.print(line); 
} 

をあきらめる前に、時間の少なくとも一定量を待つ確保するために、この線に沿って何かを行うことができますお手伝いできるクライアントライブラリが書かれているので、このような低レベルのHTTPコードを書く必要はありません。あなたはそれを使用するいくつかの例を見つけることができますhere

関連する問題