douyi0219 2018-12-25 08:18
浏览 71
已采纳

如何修复Echo和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.

  • 写回答

3条回答 默认 最新

  • doukanmang3687 2018-12-25 13:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器