html接收nodemcu发出的数据,NodeMCU http.post请求及服务端接收不到参数解决方案

In the use of NodeMCU, problems  may be encountered that the webserver can't receive the data of "http.post" request body.

1、Using NodeJS Webserver

ESPlorer, the Lua code editor and uploader of NodeCU, may have some bugs with itself. We execute code blocks directly, it will be wrong for post request, while it will run well after uploading the saved *.lua file to NoceMCU.

2、Using PHP Webserver

Beside the above problem, $_POST['xx'] can only receive the submitted data of "Content-Type: application/x-www-form-urlencoded" formate, but "Content-Type: application/json".We can use file_get_contents("php://input") to receive the data,and because of the diffrence between data formate received from NodeMCU and HTML form,we need to parse specifically with code block as follows :

—————————————————————————————————————————

上面是练英语写作的,欢迎吐槽

tongue.gif。中文如下:

在使用NodeMCU时可能会不出现服务器无法接收到NodeMCU http.post请求参数的问题。

1、采用NodeJS服务器

ESPlorer编辑器本身可能问题,直接执行代码片段接收不到post数据,而保存到lua文件里传至mcu上执行则正常。

2、采用PHP服务器

除上诉随机存在的问题,$_POST['xx'] 只能接收Content-Type: application/x-www-form-urlencoded提交的数据,不能接收Content-Type: application/json数据,可以采用file_get_contents("php://input")来接收,而且接收到MCU与HTML表单提交的数据格式不一样,需要具体解析。代码如下:

NodeMCU客户端

http.post('http://192.168.1.106:3000',

'Content-Type: application/json\r\n',

'{"name":"hello"}',

function(code, data)

if (code < 0) then

print("HTTP request failed")

else

print(code, data)

end

end)

NodeJS服务端:

var express = require('express');

var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.urlencoded({

extended: false

}))

app.use(bodyParser.json())

app.get('/', function (req, res) {

res.send('Hello World from GET');

});

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

res.send('Hello World from POST');

console.log('Client: ', req.connection.remoteAddress);

console.log('Method: ', req.method);

console.log('Headers: ', req.headers);

console.log('Post Body: ', req.body);

})

app.listen(3000, function () {

console.log('Server is listening on port 3000!');

});

php://input方式接收HTML表单请求

$str=file_get_contents("php://input");

parse_str($str,$ar);

$user_name = isset($ar['name'])?$ar['name']: null;

$message = array("type" => 0, "name" => $user_name);

echo json_encode($message);

php://input方式接收NodeMCU请求

$str=file_get_contents("php://input");

$args=(json_decode($str));

$user_name = isset($args->name)?$args->name: null;

$message = array("type" => 0, "name" => $user_name);

echo json_encode($message);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值