登录
首页 >  Golang >  Go问答

React 的服务指南

来源:stackoverflow

时间:2024-03-16 09:03:28 199浏览 收藏

在使用 Go 服务器后端为 React 应用程序提供服务时,可能面临“此页面无法正常工作”和“本地主机已重定向太多次”的错误。这是因为需要正确设置处理程序以处理静态文件。修改代码以将构建处理程序指向目录而不是文件,并使用标准库的 `http.FileServer` 替代过时的处理程序,即可解决此问题。

问题内容

我有一个简单的 react 应用程序,我想从我的 go 服务器后端提供服务。我听说这个过程类似于提供静态 html 文件,但我似乎无法让它工作。

当我尝试在浏览器上查看应用程序时,它显示“此页面无法正常工作”并且“本地主机已重定向太多次”

这是我在本地运行服务器并尝试处理反应应用程序的代码

func main() {

r := mux.newrouter()

// handle app
buildhandler := 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,
}

// serve
fmt.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")
}

我相信解决方案很简单,而且我很可能在某个地方犯了一个小错误。


解决方案


在您的情况下,只需要构建处理程序。它必须指向目录而不是文件。除路由情况外,其余处理程序均已过时。

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")
}

今天关于《React 的服务指南》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>