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 :
—————————————————————————————————————————
上面是练英语写作的,欢迎吐槽。中文如下:
在使用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)
参考:http://nodemcu.readthedocs.io/en/dev/en/modules/http/#httppost
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!'); });
感谢网友【大桥下的蜗牛】提供NodeJS服务端代码
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);
【转载请注明出处:http://blog.csdn.net/leytton/article/details/51637375】