NodeMCU作为网页服务器

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

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

httpServer.lua是使用的这里 的HTTP服务库,界面程序使用了轻量的Zepto.js与Spectre.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如下:




    
    
    1004打卡
    


    

签到

NodeMCU作为网页服务器_第1张图片
Screenshot_2017-05-15-18-18-55-260_com.android.br.png
NodeMCU作为网页服务器_第2张图片
Screenshot_2017-05-15-18-19-05-761_com.android.br.png

你可能感兴趣的:(NodeMCU作为网页服务器)