服务器端代码实现

提供静态⻚⾯:

1
2
3
4
5
6
7
router.addRoute("GET", "/login", [this](const HttpRequest& req) {
HttpResponse response;
response.setStatusCode(200);
response.setHeader("Content-Type", "text/html");
response.setBody(readFile("path/to/login.html")); // 读取 HTML ⽂件
return response;
});

处理表单提交:

1
2
3
4
5
6
router.addRoute("POST", "/login", [&db](const HttpRequest& req) {
auto params = req.parseFormBody();
std::string username = params["username"];
std::string password = params["password"];
// 进⾏登录验证...
});

readFile实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
std::string readFile(const std::string& filePath) {
// 使⽤标准库中的ifstream打开⽂件
std::ifstream file(filePath);

// 判断⽂件是否成功打开
if (!file.is_open()) {
// 若未能成功打开⽂件,返回错误信息
return "Error: Unable to open file " + filePath;
}

// 使⽤stringstream来读取⽂件内容
std::stringstream buffer;

// 将⽂件内容读⼊到stringstream中
buffer << file.rdbuf();

// 将读取的内容转换为字符串并返回
return buffer.str();
}