http-server
约 474 字大约 2 分钟
2024-05-31
BeShell 集成了 Mongoose 库,支持 HTTP、WebSocket、MQTT 等网络协议。借助文件系统模块,可以像在 Node.js 中一样开发 Web 应用。
详细 API 请参考 Mongoose API。
基础代码
C++ 初始化
#include <BeShell.hpp>
using namespace be ;
BeShell beshell ;
void app_main() {
// 应用 Mongoose、WiFi 和文件系统模块
beshell.use<Mg>() ;
beshell.use<WiFi>() ;
beshell.use<FS>() ;
// 挂载分区
FS::mount("/", new LittleFS("fsroot", true)) ;
// 启动 BeShell
beshell.setup() ;
// 自动运行 main.js
beshell.engine->evalScript("/main.js") ;
beshell.run() ;
}JS 初始化
import * as wifi from "wifi"
import { HTTPServer } from "mg"简单 HTTP 服务器
import * as wifi from "wifi"
import { HTTPServer } from "mg"
;(async () => {
// 启动热点
if (!await wifi.startAP("BeShell-APP", "12345678")) {
console.log("Failed to start AP")
return
}
console.log("AP started")
// 创建 HTTP 服务器
const server = new HTTPServer()
server.setHandler((ev, req, res) => {
if (ev === "http.msg") {
// 动态路由
if (req.uri() === "/hello") {
res.reply("<h3>Hello World</h3>")
}
// 静态文件服务
else {
res.serveDir(req, "/public")
}
}
})
// 监听 80 端口
server.listen("0.0.0.0:80")
console.log("Server running at http://192.168.4.1")
})()用手机或电脑连接热点,打开浏览器访问 http://192.168.4.1/hello。
通过 BeConsole 在 ESP32 上创建 public 目录并上传文件,即可访问静态页面。
处理 GET/POST 请求
import { HTTPServer, HTTPRequest, HTTPResponse } from "mg"
const server = new HTTPServer()
server.setHandler((ev, req, res) => {
if (ev === "http.msg") {
const path = req.uri()
if (path === "/api/data") {
// 返回 JSON 数据
res.writeHead(200, { "Content-Type": "application/json" })
res.reply(JSON.stringify({ temperature: 25.5, humidity: 60 }))
}
else if (path === "/api/led") {
// 处理 POST 请求控制 LED
if (req.method() === "POST") {
const body = req.body()
console.log("LED control:", body)
res.reply("OK")
}
}
else {
res.serveDir(req, "/public")
}
}
})
server.listen("0.0.0.0:80")常见问题
如何获取请求参数?
// 获取 URL 参数
const query = req.url() // "/api?temp=25"
// 解析参数
const url = new URL(req.url(), "http://localhost")
const temp = url.searchParams.get("temp")
// 获取 POST body
const body = req.body()如何设置 CORS?
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
})HTTPS 如何配置?
参考 HTTPServer API 了解如何配置 HTTPS 证书。
后续内容
- WebSocket 相关文档正在整理中
- SQLite 数据库相关文档正在整理中
