go+gin部署vue的history路由项目刷新出现404的问题
因为路由只是注册在前端,当浏览器端刷新页面了,请求被发到了服务端来了。服务器找不到就404了。
go
r.Use(static.Serve("/", static.LocalFile("./vue-front/dist/", false)))
// 这里参考了:https://cong5.net/post/how-to-implement-routing-support-for-vuejs-single-page-application-in-golang-program
r.NoRoute(func(c *gin.Context) {
accept := c.Request.Header.Get("Accept")
flag := strings.Contains(accept, "text/html")
if flag {
content, err := os.ReadFile("./vue-front/dist/index.html")
if (err) != nil {
c.Writer.WriteHeader(404)
c.Writer.WriteString("Not Found")
return
}
etag := fmt.Sprintf("%x", md5.Sum(content))
c.Header("ETag", etag)
c.Header("Cache-Control", "no-cache")
// 如果客户端已经缓存了文件,则返回 304 不修改状态
if match := c.GetHeader("If-None-Match"); match != "" {
if strings.Contains(match, etag) {
c.Status(http.StatusNotModified)
return
}
}
c.Data(http.StatusOK, "text/html; charset=utf-8", content)
}
})
r.Use(static.Serve("/", static.LocalFile("./vue-front/dist/", false)))
// 这里参考了:https://cong5.net/post/how-to-implement-routing-support-for-vuejs-single-page-application-in-golang-program
r.NoRoute(func(c *gin.Context) {
accept := c.Request.Header.Get("Accept")
flag := strings.Contains(accept, "text/html")
if flag {
content, err := os.ReadFile("./vue-front/dist/index.html")
if (err) != nil {
c.Writer.WriteHeader(404)
c.Writer.WriteString("Not Found")
return
}
etag := fmt.Sprintf("%x", md5.Sum(content))
c.Header("ETag", etag)
c.Header("Cache-Control", "no-cache")
// 如果客户端已经缓存了文件,则返回 304 不修改状态
if match := c.GetHeader("If-None-Match"); match != "" {
if strings.Contains(match, etag) {
c.Status(http.StatusNotModified)
return
}
}
c.Data(http.StatusOK, "text/html; charset=utf-8", content)
}
})