Home > Backend Development > Golang > How to Handle 404 Errors When Serving a React Frontend with a Go Backend?

How to Handle 404 Errors When Serving a React Frontend with a Go Backend?

Barbara Streisand
Release: 2024-12-14 15:26:15
Original
148 people have browsed it

How to Handle 404 Errors When Serving a React Frontend with a Go Backend?

How to Implement Frontend Routing in Go Applications

Problem:

When accessing a specific path (/my_frontend_path) directly in your browser for a Go application serving React frontend, you encounter a 404 error. This is because the Go server does not recognize the path, leading to a request for the page from the server.

Solution:

To delegate unrecognized paths to the frontend react router, you can implement one of several approaches:

1. Hash History

Hash history is recommended in the linked question and involves adding # to the URL for client-side routing. This ensures that the server does not interpret the path and allows the frontend router to handle it.

2. Catch-All Approach

For a purely server-side solution, you can implement a catch-all approach that returns index.html for any unrecognized path. This ensures that the frontend application is loaded and the router can detect and route the path accordingly.

Here's how you can implement it in Go:

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 then return if; 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)
}
Copy after login

Note: This approach will return index.html for all unrecognized paths, including non-existent files. You can consider adding limitations, such as checking file extensions, if this poses an issue.

The above is the detailed content of How to Handle 404 Errors When Serving a React Frontend with a Go Backend?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template