I am creating a web app that makes use of the amazon product advertising API. I haven’t started on this part of the functionality as I am still creating the base web app. I have already created a desktop app version in python with CTkinter so I’m using this as a design aid to help me. For the web app I have decided to use Fast-API to connect the frontend to my python backend and my MySQL database instance hosted on the google cloud. I have managed to create the first few endpoints that handle user logins. Now I am starting to create the endpoints that control the user data stored in the SQL DB; I wanted to start with a simple request at first to ease myself into the more complicated stuff so I am currently trying to set up a theme switcher (to switch the web app theme from dark mode to light mode).
I started to set it up the same as my other POST requests, with CORS middleware setup, ensuring the request has the same name in the frontend as the backend and is pointing to the correct request URL. However, it continually gives me error 404 when testing. I have tried all sorts including setting up the CORS Middleware the same as the other requests that all work; Setting up the app.options for this specific request; trying different sql statements, using logging to show where it fails, clearing by browser cache/using incognito window etc etc. After 2 days of trying this I have given up with this and wish for someone to read my frontend, backend and middelware setup for this specific request to see if I’m missing something extremely obvious.
Please find my project code below:
# Python / Fast-API
# Middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Your frontend origin
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Pydantic model to handle the incoming data
class ThemeUpdateRequest(BaseModel):
username: str
# Options for Update-Theme
@app.options("/update-theme/")
async def options_update_theme():
return {
"allow": "POST, OPTIONS",
"access-control-allow-origin": "http://localhost:5500",
"access-control-allow-methods": "POST, OPTIONS",
"access-control-allow-headers": "Content-Type, Authorization"
}
# POST Request /update-theme/
@app.post("/update-theme/")
def update_theme(data: ThemeUpdateRequest, connection=Depends(get_connection)):
try:
print(f"Received request to /update-theme/ for user:{data.username}")
with connection.cursor() as cursor:
# Fetch the current theme value for the user
cursor.execute("SELECT light_dark FROM user_frame WHERE username = %s", (data.username,))
theme_value = cursor.fetchone()
if theme_value is None:
print(f"/update-theme/ failed due to no user frame found for user: {data.username}")
insert_frame(connection, data.username)
cursor.execute("SELECT light_dark FROM user_frame WHERE username = %s", (data.username,))
theme_value = cursor.fetchone()
# Toggle the theme value
new_theme_value = 1 if theme_value[0] == 0 else 0
# Update the theme in the database
cursor.execute("UPDATE user_frame SET light_dark = %s WHERE username = %s", (new_theme_value, data.username))
connection.commit()
print(f" Theme has been updated to {new_theme_value} for user:{data.username}")
return {"status": "Theme updated successfully", "new_theme_value": new_theme_value}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to Update Theme: {str(e)}")
# JavaScript
const toggleThemeButton = document.getElementById("toggle-theme")
toggleThemeButton.addEventListener("click", async function () {
const username = localStorage.getItem("username")
if (!username) {
errorMessage.textContent = "Username not found. Please log in first."
return
}
try {
console.log("Sending request to update theme")
const response = await fetch("http://localhost:8000/update-theme/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
})
console.log("Response received:", response)
if (response.ok) {
const result = await response.json()
document.body.classList.toggle("dark-mode", Number(result.new_theme_value) === 1)
errorMessage.textContent = ""
} else {
const errorData = await response.json()
console.error("Error data:", errorData)
errorMessage.textContent = errorData.detail || "Failed to update theme."
}
} catch (error) {
console.error("Fetch error:", error)
errorMessage.textContent = "An error occurred while updating the theme."
}
})
Furthermore, once I have got this theme switching button working I am going to add functionality to my login function that will automatically change the theme to the last theme the user was using, essentially keeping their preferences saved.