Issue
I'm working on a project with a Flask backend and a React frontend, but I'm encountering a routing problem.
Only the main route ("/"
) seems to be working as expected. When I try to access another route, like "/sign-in"
, I don't receive an error, but I get redirected back to the main page ("/"
). Even routes that do not exist seem to redirect me to the main page instead of returning a 404 error.
This is my backend:
# Serve static files
@app.route("/")
@app.route("/<path:path>")
def serve_static(path=""):
return app.send_static_file("index.html")
@app.route("/favicon.ico")
def favicon():
return app.send_static_file('favicon.ico')
@app.route("/assets/<path:path>")
def assets(path):
return send_from_directory("static/assets", path)
My react router:
export default function App() {
return (
<HashRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Chat />} />
<Route path="*" element={<NoPage />} />
</Route>
<Route path="/sign-in">
<Route index element={<SignInStart />} />
</Route>
</Routes>
</HashRouter>
);
}
Solution
Few things first:
- Make sure you are using the proper hash urls. In your case you have used
HashRouter
. It is different fromBrowserRouter
. - Make sure you are using
Outlet
in your Layout page.
Working example:
import "./styles.css";
import { HashRouter, Route, Routes, Outlet } from "react-router-dom";
const Layout = () => (
<>
<p>Layout</p>
<hr />
<Outlet />
</>
);
const Chat = () => <p>Chat</p>;
const NoPage = () => <p>NoPage</p>;
const SignInStart = () => <p> SignInStart</p>;
export default function App() {
return (
<HashRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Chat />} />
<Route path="*" element={<NoPage />} />
</Route>
<Route path="/sign-in">
<Route index element={<SignInStart />} />
</Route>
</Routes>
</HashRouter>
);
}
- Url:
https://example.com/#/sign-in
will render sign in page - Url:
https://example.com/
will render Chat page - Url:
https://example.com/#/nonexistentroute
will render No Page.
If you don't require hashed urls, consider moving to BrowserRouter instead which can understand normal URLs.
Answered By - ray
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.