深圳网站建设联系方式,用iis制作简单网站,建筑猎头网,高校网站建设需求单ESP32-Web-Server编程- 实现 Web 登录网页
概述
是时候实现更加安全的网页了。登录机制是最简单的控制网页访问权限的方法。
需求及功能解析
本节演示如何在 ESP32 上部署一个 Web 服务器#xff0c;并建立登录页面的机制#xff0c;用户可以实现登录、登出的功能#x…ESP32-Web-Server编程- 实现 Web 登录网页
概述
是时候实现更加安全的网页了。登录机制是最简单的控制网页访问权限的方法。
需求及功能解析
本节演示如何在 ESP32 上部署一个 Web 服务器并建立登录页面的机制用户可以实现登录、登出的功能控制通过网页访问 ESP32 的内部信息的权限。
目录结构
├── CMakeLists.txt
├── main
│ ├── CMakeLists.txt
│ └── main.c User application
├── components
│ └── fs_image
└── README.md This is the file you are currently reading目录结构主要包含主目录 main以及组件目录 components.其中组件目录components中包含了用于存储网页文件的 fs_image 目录即前述前端文件。
前端代码
登录机制的实现主要是在 JS 文件内。首先在 components/fs_image/web_image/js/index.js 中设置了检查函数通过检查 是否使能了 login_user来判断是否跳转到登录界面 login.html.
$(function(){if(!sessionStorage.getItem(login_user)){window.location ./login.html;}$(#logout).click(function(){var xhr new XMLHttpRequest();xhr.open(GET, ./logout, true);xhr.send();setTimeout(function(){ window.open(/logged-out,_self); }, 1000);})
})然后在 components/fs_image/web_image/login.html 中设计登录界面登录界面包含登录需要的 logemail、password 输入框和登录提交 submit 按钮。
div classform-groupinput typeemail namelogemail classform-style placeholder账号 idloginuser autocompleteoffi classinput-icon uil uil-at/i
/div
div classform-group mt-2input typepassword namelogpass classform-style placeholder密码 idloginpwd autocompleteoffi classinput-icon uil uil-lock-alt/i
/div
a href# idsubmit classbtn mt-4提交/a在点击提交时会触发 components/fs_image/web_image/js/login.js 中的提交帐号、密码的函数 submit().
后端代码
后端代码主要是增加了校验前端网页提交的帐号、密码的函数 login_post_handler()。
{/loginpwd, HTTP_POST, login_post_handler, rest_context},在该函数中接收推动数据并解析推送数据中的帐号、密码
static esp_err_t login_post_handler(httpd_req_t* req)
{char user[USER_NAME_MAX_LEN];char password[PASSWORD_MAX_LEN];char* buf ((rest_server_context_t*) (req-user_ctx))-scratch;int str_len 0;if (recv_post_data(req, buf) ! ESP_OK) {web_response_error(req, HTTPD_500);ESP_LOGE(TAG, recv post data error);goto error_handle;return ESP_FAIL;}str_len httpd_find_arg(buf, loginuser, (char *)user, sizeof(user), false);if ((str_len -1) || (strlen((char *)user) 0)) {ESP_LOGE(TAG, user is abnormal);goto error_handle;} else {if (web_str_check(user, web_user_name) ! true) {ESP_LOGE(TAG, user_name is wrong);goto error_handle;}}str_len httpd_find_arg(buf, loginpwd, (char *)password, sizeof(password), false);if ((str_len -1) || (strlen((char *)password) 0)) {ESP_LOGE(TAG, loginpwd is abnormal);goto error_handle;} else {if (web_str_check(password, web_pwd) ! true) {ESP_LOGE(TAG, loginpwd is wrong);goto error_handle;}}web_response_OK(req);return ESP_OK;
error_handle:web_response_error(req, HTTPD_400);return ESP_FAIL;
}默认帐号、密码是
static char web_user_name[USER_NAME_MAX_LEN] laowang;
static char web_pwd[PASSWORD_MAX_LEN] esp32;示例效果 点击右上脚的“退出”按钮可以退出该网页: 讨论
总结
1本节主要是介绍在 ESP32 Web 上部署登录、登出功能的网页通过登录机制可以控制访问 ESP32 Web 的权限。
资源链接
1ESP32-Web-Server ESP-IDF系列博客介绍 2对应示例的 code 链接 点击直达代码仓库
3下一篇
(码字不易感谢点赞或收藏)