小编典典

生产中的Vue路由器(与Go一起使用)

go

我想将客户端和服务器完全分开,所以我用创建了一个vuejs项目vue init webpack my-project。在这个项目中,我使用vue-
router进行所有路由(这包括特殊路径,例如/user/SOMEID..

这是我的routes.js文件:

import App from './App.vue'

export const routes = [
  {
    path: '/',
    component: App.components.home
  },
  {
    path: '/user/:id',
    component: App.components.userid
  },
  {
    path: '*',
    component: App.components.notFound
  }
]

当我运行应用程序时,npm run dev一切运行正常。我现在准备部署到云,所以我就跑了npm run build。由于我需要使用HTTP服务器,因此我决定也使用Go。.这是我的Go文件:

package main

import (
    "fmt"
    "github.com/go-chi/chi"
    "github.com/me/myproject/server/handler"
    "net/http"
    "strings"
)

func main() {
    r := chi.NewRouter()

    distDir := "/home/me/code/go/src/github.com/me/myproject/client/dist/static"
    FileServer(r, "/static", http.Dir(distDir))

    r.Get("/", IndexGET)

    http.ListenAndServe(":8080", r)
}

func IndexGET(w http.ResponseWriter, r *http.Request) {
    handler.Render.HTML(w, http.StatusOK, "index", map[string]interface{}{})
}

func FileServer(r chi.Router, path string, root http.FileSystem) {
    if strings.ContainsAny(path, "{}*") {
        panic("FileServer does not permit URL parameters.")
    }

    fs := http.StripPrefix(path, http.FileServer(root))

    if path != "/" && path[len(path)-1] != '/' {
        r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
        path += "/"
    }
    path += "*"

    r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fs.ServeHTTP(w, r)
    }))
}

我可以加载App.components.home似乎一切正常的主页()(css,图像,翻译,对服务器的调用和来自服务器的响应)..但是当我尝试打开其他路线时,结果要么是404,要么是加载用户,然后我得到404 page not found纯文本的响应(不是应该呈现的vue notFound组件)。

任何想法我在做什么错以及如何解决?


编辑:这是main.js文件中路由器设置的另一部分:

const router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes
})

new Vue({
  el: '#app',
  router,
  i18n,
  render: h => h(App)
})

阅读 452

收藏
2020-07-02

共1个答案

小编典典

我可能是错的,但是也许您尝试访问的路由在服务器(在Go http服务器中)中已解析。

您可以尝试mode: 'history'在vue-
router初始化中删除,以使其默认为hashmode(然后路由将在浏览器中解析)。请参阅链接。

2020-07-02