The inability to access frontend paths using URLs like http://localhost:8090/my_frontend_path when running both the Go backend and the React frontend can be attributed to a fundamental issue:
When you access http://localhost:8090/my_frontend_path from the browser, the frontend React router is not active yet. Hence, the browser requests the page from the server. However, my_frontend_path doesn't exist in the build folder, leading to a 404 "Page Not Found" error.
One straightforward way to rectify this issue is by implementing a "catch-all" approach at the Go server level. This involves returning index.html (and consequently your app) for any paths that aren't explicitly handled elsewhere. Here's an example:
const FSPATH = "./build/" func main() { fs := http.FileServer(http.Dir(FSPATH)) http.HandleFunc("/my_api", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("API CALL")) }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // If the requested file exists, return it; otherwise return index.html (fileserver default page) if r.URL.Path != "/" { fullPath := FSPATH + strings.TrimPrefix(path.Clean(r.URL.Path), "/") _, err := os.Stat(fullPath) if err != nil { if !os.IsNotExist(err) { panic(err) } // Requested file does not exist so we return the default (resolves to index.html) r.URL.Path = "/" } } fs.ServeHTTP(w, r) }) http.ListenAndServe(":8090", nil) }
This code checks for the requested file's existence. If it doesn't exist, it changes the requested path to "/", which will redirect to index.html and allow the React router to handle the routing.
Another option is to employ hash history for your React application. With this method, the initial request to the my_frontend_path URL will not interact with the Go server. Instead, it will be handled entirely by the React router. Hash history can be configured in your React app's createBrowserHistory or createHashHistory functions.
The above is the detailed content of How Can I Fix '404 Not Found' Errors When Routing a React Frontend with a Go Backend?. For more information, please follow other related articles on the PHP Chinese website!