From 8c761c64368b9eafb4c7908195004e8459d71e5a Mon Sep 17 00:00:00 2001 From: Benjamin Bolte Date: Wed, 29 May 2024 14:27:56 -0400 Subject: [PATCH] fix fastapi routing mismatch with react routing --- Makefile | 3 +++ store/app/main.py | 22 ++++++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 7a0d77be..f2c24ae4 100644 --- a/Makefile +++ b/Makefile @@ -29,6 +29,9 @@ all: start-fastapi: @fastapi dev 'store/app/main.py' --port 8080 +start-frontend-rebuild: + @cd frontend && npm run watch + start-docker: @docker kill store-db || true @docker rm store-db || true diff --git a/store/app/main.py b/store/app/main.py index 62dc0b80..7a816cd7 100644 --- a/store/app/main.py +++ b/store/app/main.py @@ -4,7 +4,7 @@ from fastapi import FastAPI, Request, status from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import JSONResponse +from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from store.app.api.routers.main import api_router @@ -16,6 +16,15 @@ if not (FRONTEND_BUILD_DIR := FRONTEND_DIR / "build").exists(): raise FileNotFoundError(f"Frontend is not built to {FRONTEND_BUILD_DIR}") +FRONTEND_STATIC_DIR = FRONTEND_BUILD_DIR / "static" +if not FRONTEND_STATIC_DIR.exists(): + raise FileNotFoundError(f"Frontend static files not found at {FRONTEND_STATIC_DIR}") + +FRONTEND_INDEX_FILE = FRONTEND_BUILD_DIR / "index.html" +if not FRONTEND_INDEX_FILE.exists(): + raise FileNotFoundError(f"Frontend index file not found at {FRONTEND_INDEX_FILE}") + +FRONTEND_OTHER_FILES = {f.name for f in FRONTEND_BUILD_DIR.glob("*") if f.is_file()} app.include_router(api_router, prefix="/api") @@ -29,7 +38,16 @@ async def value_error_exception_handler(request: Request, exc: ValueError) -> JS # Mounts the static frontend files to the /static path. -app.mount("/", StaticFiles(directory=FRONTEND_BUILD_DIR, html=True), name="static") +app.mount("/static", StaticFiles(directory=FRONTEND_STATIC_DIR, html=True), name="/static") + + +# Redirects all other paths to the index.html file. +@app.get("/{full_path:path}") +async def redirect_to_index(full_path: str) -> FileResponse: + if full_path in FRONTEND_OTHER_FILES: + return FileResponse(FRONTEND_BUILD_DIR / full_path) + return FileResponse(FRONTEND_INDEX_FILE) + # Adds CORS middleware. app.add_middleware(