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

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

如何服務 React

如何服務 React

Go
慕仙森 2023-07-26 16:36:25
我有一個簡單的 React 應用程序,我想從我的 Go 服務器后端提供服務。我聽說這個過程類似于提供靜態 html 文件,但我似乎無法讓它工作。當我嘗試在瀏覽器上查看該應用程序時,它顯示“此頁面無法正常工作”并且“本地主機已重定向太多次”這是我在本地運行服務器并嘗試處理反應應用程序的代碼func main() {r := mux.NewRouter()// handle appbuildHandler := http.FileServer(http.Dir("./client/build/index.html"))r.PathPrefix("/").Handler(buildHandler)staticHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("./client/build/static")))r.PathPrefix("/static/").Handler(staticHandler)r.HandleFunc("/", index).Methods("GET")srv := &http.Server{    Handler:      r,    Addr:         "127.0.0.1:8080",    WriteTimeout: 15 * time.Second,    ReadTimeout:  15 * time.Second,}// servefmt.Println("Server started on PORT 8080")log.Fatal(srv.ListenAndServe())}這是索引路由的代碼func index(w http.ResponseWriter, r *http.Request) {    // not sure if this is necessary    http.ServeFile(w, r, "index.html")}我相信解決方案很簡單,而且我很可能在某個地方犯了一個小錯誤。
查看完整描述

1 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

在您的情況下,只需要構建處理程序。它必須指向目錄而不是文件。除了路由之外,其余處理程序均已過時。


package main


import (

    "fmt"

    "github.com/gorilla/mux"

    "log"

    "net/http"

    "time"

)


func main() {


    r := mux.NewRouter()


    r.HandleFunc("/route1", index).Methods("GET")

    r.HandleFunc("/route2", index).Methods("GET")

    buildHandler := http.FileServer(http.Dir("client/build"))

    r.PathPrefix("/").Handler(buildHandler)


    srv := &http.Server{

        Handler:      r,

        Addr:         "127.0.0.1:8080",

        WriteTimeout: 15 * time.Second,

        ReadTimeout:  15 * time.Second,

    }


    fmt.Println("Server started on PORT 8080")

    log.Fatal(srv.ListenAndServe())


}


func index(w http.ResponseWriter, r *http.Request) {

    http.ServeFile(w, r, "client/build/index.html")

}

僅使用標準庫即可實現相同的效果。


package main


import (

    "fmt"

    "log"

    "net/http"

    "time"

)


func main() {


    r := http.NewServeMux()


    r.HandleFunc("/route1", index)

    r.HandleFunc("/route2", index)

    buildHandler := http.FileServer(http.Dir("client/build"))

    r.Handle("/", buildHandler)


    srv := &http.Server{

        Handler:      r,

        Addr:         "127.0.0.1:8080",

        WriteTimeout: 15 * time.Second,

        ReadTimeout:  15 * time.Second,

    }


    fmt.Println("Server started on PORT 8080")

    log.Fatal(srv.ListenAndServe())


}


func index(w http.ResponseWriter, r *http.Request) {

    http.ServeFile(w, r, "client/build/index.html")

}


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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