亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我可以在一臺服務器上托管 Angular2 前端和 Golang 后端嗎

我可以在一臺服務器上托管 Angular2 前端和 Golang 后端嗎

Go
守候你守候我 2021-12-20 15:56:30
我想用 Golang 創建 RESTful API,用 Angular2 創建前端。將通過 http 請求進行通信。Angular2 將向 Golang API 發送請求。我知道對于 Angular2,我應該運行自己的 http 服務器來進行路由和服務。我可以在一臺主機上運行 Golang 服務器,在另一臺主機上運行 Angular2 服務器并將它們連接在一起嗎?
查看完整描述

2 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

Angular2 應用程序對應一組靜態文件(依賴項和應用程序代碼)。要讓 Go 為您的應用程序提供服務,您需要添加一些代碼來提供這些文件。

似乎有可能。請參閱此鏈接:

編輯

關注您的評論:

如果您想在一臺服務器上托管 Angular2 和 golang。例如,我將可以通過鏈接 mywebsite.com 訪問網站并訪問 golang api api.mywebsite.com

我看不出有什么理由不這樣做。請注意在您的 API 中支持 CORS(在響應中發送 CORS 標頭并支持預檢請求)。請參閱這些鏈接:


查看完整回答
反對 回復 2021-12-20
?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

使用標準庫實際實現


type Adapter func(http.Handler) http.Handler


// Adapt function to enable middlewares on the standard library

func Adapt(h http.Handler, adapters ...Adapter) http.Handler {

    for _, adapter := range adapters {

        h = adapter(h)

    }

    return h

}


// 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", 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")

})


查看完整回答
反對 回復 2021-12-20
  • 2 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號