Jelajahi Sumber

Add SPA fallback to serve index.html for client-side routes

React Router needs the server to return index.html for non-API routes
that don't match a static file, so the client-side router can handle
navigation to paths like /login, /dashboard, etc.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
fszontagh 2 bulan lalu
induk
melakukan
3ef1d859e4
1 mengubah file dengan 17 tambahan dan 0 penghapusan
  1. 17 0
      src/app.cpp

+ 17 - 0
src/app.cpp

@@ -23,6 +23,7 @@
 
 #include <spdlog/spdlog.h>
 #include <filesystem>
+#include <fstream>
 
 namespace smartbotic::microbit {
 
@@ -169,6 +170,22 @@ void App::start() {
     if (serveStatic && std::filesystem::exists(staticFilesPath_)) {
         httpServer_->set_mount_point("/", staticFilesPath_);
         spdlog::info("Serving static files from {}", staticFilesPath_);
+
+        // SPA fallback: serve index.html for non-API routes that don't match a file
+        auto indexPath = std::filesystem::path(staticFilesPath_) / "index.html";
+        if (std::filesystem::exists(indexPath)) {
+            httpServer_->set_error_handler([indexPath](const httplib::Request& req, httplib::Response& res) {
+                if (res.status == 404 && req.path.substr(0, 5) != "/api/") {
+                    std::ifstream ifs(indexPath);
+                    if (ifs) {
+                        std::string body((std::istreambuf_iterator<char>(ifs)),
+                                          std::istreambuf_iterator<char>());
+                        res.set_content(body, "text/html");
+                        res.status = 200;
+                    }
+                }
+            });
+        }
     }
 
     running_ = true;