我开始尝试使用Go和Angular,但我有一个奇怪的问题.我想我只是错过了一个小细节,但我无法理解.
我正在使用https://github.com/julienschmidt/httprouter作为Go的路由器...现在使用Angular,我应该能够将URL复制并粘贴到浏览器中,Angular应该处理相应的路由,对吧?
我有一个"/ login"路线.如果通过前端访问路线,哪个有效...但如果我在浏览器中键入"mypage.com/login",则不会获得404.
Go routing基本上只是做
router.NotFound = http.FileServer(http.Dir("./public"))
Run Code Online (Sandbox Code Playgroud)
哪个适用于"/"路由,但不适用于其他任何内容.这似乎是正确的.但是如何正确设置路由,以便Angular处理所有路由?
CES*_*SCO 12
这就是我在标准Go库中使用的,并且路由工作很好.
// Creates a new serve mux
mux := http.NewServeMux()
// Create room for static files serving
mux.Handle("/node_modules/", http.StripPrefix("/node_modules", http.FileServer(http.Dir("./node_modules"))))
mux.Handle("/html/", http.StripPrefix("/html", http.FileServer(http.Dir("./html"))))
mux.Handle("/js/", http.StripPrefix("/js", http.FileServer(http.Dir("./js"))))
mux.Handle("/ts/", http.StripPrefix("/ts", http.FileServer(http.Dir("./ts"))))
mux.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./css"))))
// Do your api stuff**
mux.Handle("/api/register", util.Adapt(api.RegisterHandler(mux),
api.GetMongoConnection(),
api.CheckEmptyUserForm(),
api.EncodeUserJson(),
api.ExpectBody(),
api.ExpectPOST(),
))
mux.HandleFunc("/api/login", api.Login)
mux.HandleFunc("/api/authenticate", api.Authenticate)
// Any other request, we should render our SPA's only html file,
// Allowing angular to do the routing on anything else other then the api
// and the files it needs for itself to work.
// Order here is critical. This html should contain the base tag like
// <base href="/"> *href here should match the HandleFunc path below
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "html/index.html")
})
Run Code Online (Sandbox Code Playgroud)
您可以http直接使用该包。
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/index.html")
})
Run Code Online (Sandbox Code Playgroud)
这将为所有与路由不匹配的请求提供 index.html 文件。
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))
Run Code Online (Sandbox Code Playgroud)
这将为公共目录中的所有文件提供服务。
不要忘记启动你的服务器
http.ListenAndServe(":8000", nil)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13009 次 |
| 最近记录: |