如何从Arduino esp8226 HTTP将数据发布到Node Express API?

时间:2018-10-16 08:58:14

标签: node.js http heroku arduino esp8266

我正在通过HTTP将数据从连接到esp8226的arduino发布到Web api https://morning-cliffs-85779.herokuapp.com/api/users。我正在使用wifisp库来HTTP_POST数据。

发布后,Arduino会给出以下响应:

 Connected to server
 [WiFiEsp] Data packet send error (2)
 [WiFiEsp] Failed to write to socket 3
 [WiFiEsp] Disconnecting  3

Heroku服务器给出响应:

at=error code=H13 desc="Connection closed without response"

以下是Arduino代码:

if (client.connect(server, 80)) {
      Serial.println("Connected to server");
    // Make a HTTP request
    String content = "id=5bc58842bdfea0153bb27214&volt=7";
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
    client.println("Accept: */*");
    client.println("Content-Length: " + content.length());
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(content);
}

这是节点Express API:

app.post('/api/users', function (req, res) {

    console.log('here');

    if (req.body.id) {
        DevReading.findByIdAndUpdate(req.body.id, {
            volt: req.body.volt
        }, function (err, reading) {
            if (err) throw err;

            res.send('Update Success');
        });
    }

    else {

        var newDevReading = DevReading ({
            deviceName: 'test',
            volt: req.body.volt
        });

        newDevReading.save(function (err) {
            if (err) throw err;
            res.send('Reading Post Success');
        });
    }

});

2 个答案:

答案 0 :(得分:0)

做到了。这是代码:

if (client.connectSSL(server, 443)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    String PostData = content + volt;
    Serial.println(PostData);
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com");
    client.println("Cache-Control: no-cache");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(PostData.length());
    client.println();
    client.println(PostData);
}

希望它可以帮助某人。

答案 1 :(得分:0)

if (client.connect(server, 80)) {
  Serial.println("Connected to server");
// Make a HTTP request
String content = "id=5bc58842bdfea0153bb27214&volt=7";
client.println("POST /api/users HTTP/1.1");
client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
client.println("Accept: */*");
client.println("Content-Length: " + content.length());
client.println("Content-Type: application/x-www-form-urlencoded");
client.println();
client.println(content);
client.println('\r\n\r\n');

}

最好在元数据之后和内容之后添加下一行。您可以在这里httpServer

看到它