首页 > 解决方案 > ESP8266/NodeMCU POST 请求返回 -1 状态码

问题描述

以下代码获得 -1 的服务器响应。

我究竟做错了什么?我做了很多研究,这是建议的代码。

我已经用 Postman 测试了服务器代码,它工作正常,所以它必须是其他代码。

使用的库是ESP8266HTTPClient.h

ESP8266 代码

void loop() { 
    HTTPClient http;

    http.begin("http://localhost:3003/record");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    int httpCode = http.POST("Message");
    String payload = http.getString();

    Serial.println(httpCode);           // -1
    Serial.println(payload);            // nothing

    http.end();
}

节点快递服务器

var express = require("express");
var router = express.Router();

router.post("/record", function(req, res) {
    let message = req.body;
    console.log(message);

    res.status(200).send({
        message: message
    });
});

module.exports = router;

还尝试了一个不同的 API,有一个GET请求。还是不行。

void loop() { 
    HTTPClient http;

    http.begin("https://jsonplaceholder.typicode.com/posts/1");
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");

    int httpCode = http.GET();
    String payload = http.getString();

    Serial.println(httpCode);           // -1
    Serial.println(payload);            // nothing

    http.end();
}

标签: httparduinoesp8266nodemcu

解决方案


查看您的网址:

http://localhost:3003/记录

这意味着什么?

localhost是特殊 IP 地址的简写 - 127.0.0.1 - 表示“此主机”

您没有在 ESP8266 上运行您尝试连接的服务器,因此您不能在那里使用 localhost(ESP8266 可能无论如何都无法解析名称localhost)。

您需要将localhost替换为运行 Node Express 代码的服务器的名称或 IP 地址。


推荐阅读