首页 > 解决方案 > 将 VueJS 前端连接到 Golang 后端

问题描述

我目前正在尝试构建一个项目,其中我们有一个单独的客户端前端和后端。在这个项目中,我使用 vue-cli-service 快速创建了一个包含必要样板的 VueJS 客户端。我也在尝试使用 golang 中的 gorilla mux 路由器运行这个前端。

我的项目代码结构如下(我相信这给我带来了问题):

Multiplayer Piano 
  -> handlers (used for handling the gorilla mux routes) [Irrelevant atm]
  -> UI (Where my front-end is contained
    -> node_modules
    -> public
      -> index.html
    -> src
      -> App.vue
      -> main.js
  -> routes.go
  -> server.go (Where my main function is)

问题是,当我跑步时

go run ./

服务器已启动,我可以看到 index.html 包含在内,但 app 元素上没有安装任何内容。

server.go 目前有以下逻辑:

func main() 
{ 
  router := mux.NewRouter()

  AddAppRoutes(router)

  log.Fatal(http.ListenAndServe(":8080", router)
}

AddAppRoutes 函数在 routes.go 中,定义如下:

package main
import ...

func setStaticFolder(route *mux.Router)
{
  // What i'm trying to do here is serve our JS... however I don't think i'm doing it correctly
  // I believe this is where the issues are
  fs := http.FileServer(http.Dir("./UI/src"))
  route.PathPrefix("/UI/src").Handler(http.StripPrefix("/UI/src", fs))
}


func AddAppRoutes()
{
  setStaticFolder(route)
  // This is where we handle and serve our index.html
  route.Handlefunc("/", handlers.RenderHome)
 
}

handlers 中的 renderhome 定义如下:

func RenderHome(response http.ResponseWriter, request *http.Request)
{
  // Serving the html
  http.ServeFile(response, request, "UI/public/index.html")
}

想知道我是否可以得到一些帮助来让它工作......谢谢!

标签: javascriptvue.jsgovue-climux

解决方案


推荐阅读