我可以在一台服务器上托管 Angular2 前端和 Golang 后端吗

我想用 Golang 创建 RESTful API,用 Angular2 创建前端。将通过 http 请求进行通信。Angular2 将向 Golang API 发送请求。我知道对于 Angular2,我应该运行自己的 http 服务器来进行路由和服务。

我可以在一台主机上运行 Golang 服务器,在另一台主机上运行 Angular2 服务器并将它们连接在一起吗?


守候你守候我
浏览 184回答 2
2回答

侃侃尔雅

Angular2 应用程序对应一组静态文件(依赖项和应用程序代码)。要让 Go 为您的应用程序提供服务,您需要添加一些代码来提供这些文件。似乎有可能。请参阅此链接:https://github.com/golang/go/wiki/HttpStaticFiles编辑关注您的评论:如果您想在一台服务器上托管 Angular2 和 golang。例如,我将可以通过链接 mywebsite.com 访问网站并访问 golang api api.mywebsite.com我看不出有什么理由不这样做。请注意在您的 API 中支持 CORS(在响应中发送 CORS 标头并支持预检请求)。请参阅这些链接:http://restlet.com/blog/2015/12/15/understanding-and-using-corshttp://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/

幕布斯7119047

使用标准库实际实现type Adapter func(http.Handler) http.Handler// Adapt function to enable middlewares on the standard libraryfunc Adapt(h http.Handler, adapters ...Adapter) http.Handler {&nbsp; &nbsp; for _, adapter := range adapters {&nbsp; &nbsp; &nbsp; &nbsp; h = adapter(h)&nbsp; &nbsp; }&nbsp; &nbsp; return h}// Creates a new serve muxmux := http.NewServeMux()// Create room for static files servingmux.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", Adapt(api.RegisterHandler(mux),&nbsp; &nbsp; api.GetMongoConnection(),&nbsp; &nbsp; api.CheckEmptyUserForm(),&nbsp; &nbsp; api.EncodeUserJson(),&nbsp; &nbsp; api.ExpectBody(),&nbsp; &nbsp; 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&nbsp; &nbsp;&nbsp;// 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&nbsp;mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; http.ServeFile(w, r, "html/index.html")})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go