http - 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();
}
解决方案
查看您的网址:
这意味着什么?
localhost是特殊 IP 地址的简写 - 127.0.0.1 - 表示“此主机”
您没有在 ESP8266 上运行您尝试连接的服务器,因此您不能在那里使用 localhost(ESP8266 可能无论如何都无法解析名称localhost)。
您需要将localhost替换为运行 Node Express 代码的服务器的名称或 IP 地址。
推荐阅读
- api - API 需要验证码是设计缺陷吗?
- javafx - 从新添加的窗格中分配控制器中的 FXML 元素 - JavaFX
- php - tesseract-php 包装器在本地主机上运行时出现路径错误
- javascript - 防止在页面刷新时重置倒数计时器 - Django & JS
- reactjs - 如何在反应中的 this.state.forEach 语句中抛出错误
- excel - 在 msgbox 提示中使用 inputbox 的输入
- java - 如何从 .csv 文件中拆分数据集以在 java 中进行训练和测试?
- oracle - 如何在客户端机器上部署 oracle apex 应用程序
- api - 使用相同的 spotify 客户端密码进行协作?
- keyboard - MPLAB 不接受来自键盘的某些字符