Home:ALL Converter>FastAPI app with Angular routing returning 404 and blank page on refresh

FastAPI app with Angular routing returning 404 and blank page on refresh

Ask Time:2022-03-01T02:48:44         Author:ian

Json Formatter

I am mounting an Angular app with routing with fastAPI, and everything loads correctly the first time, but when I refresh the page that includes my Angular routing, I get a 404 error on the route.

app.mount("/app", StaticFiles(directory=str("ui/"), html=True))

# this loads the app at /app/my-angular-route
@app.get("/")
def redirect_to_app() -> RedirectResponse:
    return RedirectResponse("/app/")

# this route never gets called even though I expect it to when refreshing /app/my-angular-route
@app.get("/app/{rest_of_path:path}")
def redirect_to_app(rest_of_path) -> RedirectResponse:
    return RedirectResponse("/app/")

I believe that when it sees the /app path, it automatically goes to the mounting files instead of looking at the routes I have defined.

Is there a way to first check the routes before redirecting to the mounted static files? Also is it possible to keep my Angular routing intact (ie remember what route I’m at) when I refresh the page so that it always loads the current page and does not load blank or redirect back to the home page?

I tried using the solution in this thread but am getting the error

TypeError: cannot unpack non-iterable coroutine object

EDIT: It seems I was able to get the routes to take precedent by just moving the mount after them, but as expected this is creating a circular call of the app routes calling the mount and then the mount calling the app routes. What is the best way to point to the app mount regardless of the route, but in such a way that it then switches over to my Angular routing instead of the fastAPI routing?

Author:ian,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71299692/fastapi-app-with-angular-routing-returning-404-and-blank-page-on-refresh
yy