我正在尝试将数据从我的NodeMCU获取到Node.js服务器,但是它不起作用。但是,它与WAMP中的PHP服务器一起工作时,我在做什么错了?
我的Node.js代码:
const server = http.createServer((request, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
console.log('Got a request!');
res.end('I am working fine ok');
if (request.method === 'POST') {
console.log('Got post data');
var body = '';
request.on('data', function (data) {
console.log(data);
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
}
});
Arduino代码:
void postdata(String text) {
String postData = "msg=" + text;
//String url = "http://" + ip + "/post";
String url = "http://192.168.1.2/";
http.begin(url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
Serial.println("Sending Data :- " + text);
int httpCode = http.POST(postData);
//String payload = http.getString();
// Serial.println("httpCode: " + httpCode);
//Serial.println("payload: " +payload);
http.end();
}
循环
void loop() {
server.handleClient();
postdata("ping");
delay(3000);
// String value = String(analogRead(0));
}
不是必需的PHP,但是它可以与PHP“ wampserver文本日志”一起使用? PHP代码。
<?php
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
echo 'ok';
exit;
我得到了这样的日志(log.txt)
msg=ping
msg=ping
重复