Reputation: 93
I want to Serve React App with react router dom with echo in Go. But I'm facing a problem in routing because if I directly go to that route I get not found error
package main
import (
"fmt"
checkerror "server/checkError"
connectdb "server/connectDB"
"server/handler"
"github.com/gofor-little/env"
echo "github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
_ "github.com/lib/pq"
)
func main() {
err := env.Load(".env")
if err != nil {
fmt.Println(err.Error())
return
}
userDB := connectdb.UserDB{Name: "Hi", DBP: nil}
err = userDB.ConnectDB()
fmt.Println(userDB.DBP)
checkerror.Checkerror(err)
e := echo.New()
e.Static("/","build")
e.Use(middleware.Logger())
handler.Apihandler(e, userDB.DBP)
e.File("/","index.html")
e.Logger.Fatal(e.Start(":1323"))
defer func() {
fmt.Println("DB disconnected")
userDB.CloseDB()
}()
}
This is code to serve the app Please help
I want to get access of routes from react
Upvotes: 3
Views: 843
Reputation: 13
To add to the previous answer. When e.Static
serves files directly, echo mux intercepts the routes and rejects them. Hence you see the 'Not found' error.
Upvotes: 0
Reputation: 93
Instead of serving static files using static use the middleware of StaticWith config so it can redirect to index.HTML if route is not found
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
Skipper: nil,
// Root directory from where the static content is served.
Root: "build",
// Index file for serving a directory.
// Optional. Default value "index.html".
Index: "index.html",
// Enable HTML5 mode by forwarding all not-found requests to root so that
// SPA (single-page application) can handle the routing.
HTML5: true,
Browse: false,
IgnoreBase: false,
Filesystem: nil,
}))
Upvotes: 2