NodeMCU作为网页服务器

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

程序总共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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个前端程序猿,下面这些站会让你眼前一亮。 amazeui框架组建丰富 http://amazeui.org...
    欧巴冰冰阅读 8,919评论 18 303
  • 报这个拆书课程学习的原因是最近看书,看完之后完全忘记了这个书说的是啥,各种生涩,只能通过当时读书的过程所划下的横线...
    Juzid055阅读 177评论 0 0
  • 我记得波伏瓦说过:女人,是变成的。其实,男人也是。而且,你会发现,每个人变成成年之后,当然我说的是心智模式和性格等...
    上善若水_75c4阅读 286评论 0 0
  • 一早加昨晚看完了村上春树的 《当我谈跑步时我在谈什么》,看这本书完全是在看杨熹文的公众号时被种的草,这本书读起...
    菜菜的星辰大海阅读 476评论 0 1
  • 每到开学季,包书皮都是开学要做的第一个家庭作业。 我小时候包书皮,都是用完的挂历纸或是牛皮纸来包。开始,都是妈妈帮...
    一人独占一江水阅读 230评论 3 1