美文网首页
NodeMCU作为网页服务器

NodeMCU作为网页服务器

作者: ve_故食 | 来源:发表于2017-05-15 18:05 被阅读660次

借鉴 这篇文章 做了一个简单的服务程序。

程序总共5个文件:httpServer.luaindex.htmlinit.luaspectre.csszepto.js

httpServer.lua是使用的这里 的HTTP服务库,界面程序使用了轻量的Zepto.jsSpectre.css来搭建前端页面。其中Spectre.css删掉了大部分没有用到的功能。

首先是init文件的编写:
建立一个WiFi并打开HTTP服务

wifi.setmode(wifi.SOFTAP)
cfg = {}
cfg.ssid = "1004"
cfg.pwd = "10041004"
wifi.ap.config(cfg)
print(wifi.ap.getip())
-- Serving static files
dofile('httpServer.lua')
httpServer:listen(80)

处理对应的请求:

httpServer:use('/log', function(req, res)
    res:sendFile('1004.log')
end)    
-- 返回记录的登陆log信息
httpServer:use('/login', function(req, res)
    if req.query.name ~= nil and req.query.email ~= nil then
        print('Hello: ' .. req.query.name.. req.query.email)
        if file.open("1004.log", "a+") then
            file.write('Name :  '..req.query.name..'\n')
            file.write('Email:  '..req.query.email..'\n')
            file.write('---\n')
            file.close()
        end
--将提交的表单写入log保存
        print('LOG OK')
    else
        res:send('hello')
    end
end)

访问根目录返回的index.html如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>1004打卡</title>
    <link href="spectre.css" rel="stylesheet">
</head>
<body>
    <h1>签到</h1>
    <section class="section">
    <form>
        <div class="form-group">
            <label class="form-label" for="input-name">名字</label>
            <input id="name" class="form-input" id="input-name" placeholder="名字">
            <label class="form-label" for="input-email">邮箱</label>
            <input id="email" class="form-input" id="input-email" placeholder="邮箱">
        </div>
            <button type="button" id="connect" class="btn btn-primary float-right">提交</button>
    </form>
    </section>
    <script src="zepto.min.js"></script>
    <script>
        String.prototype.format = function() {
            var args = arguments;
            return this.replace(/\{(\d+)\}/g
                , function(m,i) {
                    return args[i];
            });
        }
        $(function() {
            $('#connect').click(function() {
                $.get('../login?name={0}&email={1}'.format($('#name').val(), $('#email').val()));
                alert('签到成功!')
            })
        })
    </script>
</body>
</html>
Screenshot_2017-05-15-18-18-55-260_com.android.br.png Screenshot_2017-05-15-18-19-05-761_com.android.br.png

相关文章

网友评论

      本文标题:NodeMCU作为网页服务器

      本文链接:https://www.haomeiwen.com/subject/qxwhxxtx.html