• C++用Crow实现一个简单的Web程序,实现动态页面,向页面中输入数据并展示


    Crow是一个轻量级、快速的C++微框架,用于构建Web应用程序和RESTful API。

    将处理前端页面的POST请求以添加数据的逻辑添加到 `/submit` 路由中,并添加了一个新的路由 `/` 用于返回包含输入框、按钮和表格的完整页面。当用户向表格添加数据时,JavaScript会发送POST请求到 `/submit` 路由,后端会处理数据并将其添加到数据向量中。另外,当页面加载时,JavaScript会发送GET请求到 `/table` 路由,以获取更新后的表格数据 。

    1. #include
    2. #include
    3. #include
    4. #include
    5. std::vector data;
    6. int main() {
    7. crow::SimpleApp app;
    8. // 添加数据的页面
    9. CROW_ROUTE(app, "/")
    10. ([] {
    11. std::ostringstream os;
    12. os << "";
    13. os << "

      Add Data to Table

      "
      ;
    14. os << "";
    15. os << "";
    16. os << "";
    17. os << "
    18. ";
    19. for (const auto& item : data) {
    20. os << "
    21. ";
    22. }
    23. os << "
    24. Data
      " << item << "
      "
      ;
    25. os << "";
    26. os << "";
    27. return crow::response(os.str());
    28. });
    29. // 处理提交数据的路由
    30. CROW_ROUTE(app, "/submit")
    31. .methods("POST"_method)
    32. ([](const crow::request& req) {
    33. crow::json::rvalue json = crow::json::load(req.body);
    34. if (!json) {
    35. return crow::response(400);
    36. }
    37. std::string dataValue = json["data"].s();
    38. data.push_back(dataValue);
    39. return crow::response(200);
    40. });
    41. // 返回更新后的表格数据
    42. CROW_ROUTE(app, "/table")
    43. ([] {
    44. std::ostringstream os;
    45. for (const auto& item : data) {
    46. os << "" << item << "";
    47. }
    48. return crow::response(os.str());
    49. });
    50. app.port(8080).multithreaded().run();
    51. }

    运行效果: 

    嗯....好吧,一般人是不会在后端代码里面嵌套这么一大坨html代码的对吧,所有我们将它们分离开来。

    将html和js代码提取到index.html文件中。

    1. html>
    2. <html>
    3. <head>
    4. <title>Data Tabletitle>
    5. head>
    6. <body>
    7. <h1>Add Data to Tableh1>
    8. <input type='text' id='dataInput' placeholder='Enter data'>
    9. <button onclick='addData()'>Add Databutton>
    10. <table id='dataTable'>
    11. <tr><th>Datath>tr>
    12. table>
    13. <script>
    14. function addData() {
    15. var input = document.getElementById('dataInput');
    16. var data = input.value;
    17. var xhr = new XMLHttpRequest();
    18. xhr.open('POST', '/submit', true);
    19. xhr.setRequestHeader('Content-Type', 'application/json');
    20. xhr.send(JSON.stringify({ data: data }));
    21. xhr.onload = function () {
    22. if (xhr.status === 200) {
    23. input.value = '';
    24. fetchData();
    25. }
    26. };
    27. }
    28. function fetchData() {
    29. var table = document.getElementById('dataTable');
    30. var xhr = new XMLHttpRequest();
    31. xhr.open('GET', '/table', true);
    32. xhr.send();
    33. xhr.onload = function () {
    34. if (xhr.status === 200) {
    35. table.innerHTML = 'Data' + xhr.responseText;
    36. }
    37. };
    38. }
    39. fetchData();
    40. script>
    41. body>
    42. html>

    cpp文件中的代码修改如下。 

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. std::vector data;
    7. int main() {
    8. crow::SimpleApp app;
    9. // 提供HTML文件
    10. CROW_ROUTE(app, "/")
    11. ([] {
    12. std::ifstream t("index.html");
    13. std::string html((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
    14. crow::response response(html);
    15. response.add_header("Content-Type", "text/html");
    16. return response;
    17. });
    18. // 处理提交数据的路由
    19. CROW_ROUTE(app, "/submit")
    20. .methods("POST"_method)
    21. ([](const crow::request& req) {
    22. crow::json::rvalue json = crow::json::load(req.body);
    23. if (!json) {
    24. return crow::response(400);
    25. }
    26. std::string dataValue = json["data"].s();
    27. data.push_back(dataValue);
    28. return crow::response(200);
    29. });
    30. // 返回更新后的表格数据
    31. CROW_ROUTE(app, "/table")
    32. ([] {
    33. std::ostringstream os;
    34. for (const auto& item : data) {
    35. os << "" << item << "";
    36. }
    37. return crow::response(os.str());
    38. });
    39. app.port(8080).multithreaded().run();
    40. }

    如果在浏览器中访问 `http://localhost:8080` 时只看到HTML源代码而不是页面内容,而且状态码是200,这可能是因为浏览器没有正确解析HTML内容,一种可能的原因是浏览器接收到的数据的Content-Type头部不正确,导致浏览器将其视为纯文本而不是HTML。可以尝试在Crow应用程序中为返回的HTML内容设置正确的Content-Type头部。

    可以达到相同的效果。 

  • 相关阅读:
    本周大新闻|7-11便利店测试AR远程购物,PICO商店支持退款
    【操作系统】:操作系统概述
    Docker(八)—— Dockerfile制作Tomcat镜像
    iOS 创建PDF文件
    linux进程管理
    动态规划步骤
    论文复现——LaMa:Resolution-robust Large Mask Inpainting with Fourier Convolutions
    硬核!Apache Hudi Schema演变深度分析与应用
    vue引入element-plus显示找不到import ‘element-plus/dist/index.css‘
    Vulnhub靶机:TOMATO_ 1
  • 原文地址:https://blog.csdn.net/weixin_74027669/article/details/139999479