fis*_*ker 3 go vue.js vue-router vuejs2 go-chi
我想完全分离客户端和服务器,所以我创建了一个带有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
}
]
Run Code Online (Sandbox Code Playgroud)
当我使用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)
}))
}
Run Code Online (Sandbox Code Playgroud)
我能够加载主页 ( 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)
})
Run Code Online (Sandbox Code Playgroud)