Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix refreshing error with Echo and Angular

I'm setting up a web server with Go (using Echo) as the backend and Angular 6 as the frontend. What I do is make a simple app using Angular-cli 'ng new my-app', add a helloworld component and a '/helloworld' route and then build it into production with 'ng build --prod' which output as 'dist' folder. Folder structure:

dist
├── assets
│   ├── icons
│   └── logo.png
├── favicon.ico
├── index.html
├── main.js
├── polyfills.js
├── runtime.js
└── styles.css

I then have Go serve the static files in that 'dist' folder with following code main.go

func main() {
    e := echo.New()
    e.Static("/", "dist")
    e.File("/", "dist/index.html")
    e.Start(":3000")
}

Now when I use the browser and go to 'localhost:3000/' then the page will be serve correctly, I can navigate around using href thanks to Angular routing ,for example to: 'localhost:3000/home' the page will show correctly but if I try refreshing it then Echo will return a page content that shows:

{"message":"Not Found"}

I know I can setup the route manually like this:

e.File("/home","dist/index.html")

However if I have a lot more routes then its quite a hassle to do all that.

What I need is that any route that's not defined for Echo will be map to 'index.html'. I did try with:

e.File("/*", "dist/index.html")

and

e.GET("/*", func(c echo.Context) 
    return c.File("dist/index.html")
})

but then I get a blank page with error

"Uncaught SyntaxError: Unexpected token <  " 

with all 3 files main.js, polyfill.js and runtime.js

I'm new to Echo so I don't know how to do this.

like image 556
Tuan Nguyen Avatar asked Dec 25 '18 08:12

Tuan Nguyen


1 Answers

The problem isn't strictly related to Echo. The way Angular does routing is that it does NOT request the page from the server. It changes the URL without actually requesting another page from the server.

Thus when you go to "/home", then refresh, your browser will try to reach the server and ask it for "/home" (in contrast to the first time, the browser requests "/" which is mapped to "dist/index.html"). "/home" is not found or defined in Echo routing. Hence you get a Not Found message.

What I recommend that you do is to do the following regarding routing

e.Static("/dist", "dist")
e.File("/*", "dist/index.html")
e.Start(":3000")

And inside your index.html add "/dist" before the URLs of the requested resources.

like image 107
Seaskyways Avatar answered Sep 30 '22 14:09

Seaskyways