【问题标题】:How to set up a route to serve reactjs app?如何设置路由来服务 reactjs 应用程序?
【发布时间】:2018-10-05 02:28:39
【问题描述】:

我正在尝试设置一个路由来为我的 reactjs 应用程序提供服务。

我的 index.html 和 bundle.js 在公共文件夹中

/public/index.html
/public/bundle.js

我使用 go 作为我的后端 API,也为我的 reactjs 应用程序提供服务。

我为我的应用创建了一个子路由,例如:

r := mux.NewRouter()

app := r.Host("app.example.com").Subrouter()

因此,任何以 app 作为子域的请求都将针对我的 Reactjs 应用。

所以现在我必须为每个请求提供服务,而不管我的 reactjs 应用程序的 URL 是什么。

这里需要路径前缀吗?

我试过了:

app.PathPrefix("/").Handler(serveReact)

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

但我收到此错误:

不能使用 serveReact (type func() http.Handler) 作为类型 http.Handler 在 app.PathPrefix("/").Handler 的参数中: func() http.Handler 确实 没有实现http.Handler(缺少ServeHTTP方法)

【问题讨论】:

    标签: reactjs go gorilla mux


    【解决方案1】:

    您的 http 处理程序需要一个 ServeHTTP 方法。如果你将你的函数传递给http.HandlerFunc,那将为你介绍:

    app.PathPrefix("/").Handler(http.HandlerFunc(serveReact))
    
    func serveReact(w http.ResponseWriter, r *http.Request) {
    }
    

    HandlerFunc 类型是一个适配器,允许将普通函数用作 HTTP 处理程序。如果 f 是具有适当签名的函数,则 HandlerFunc(f) 是调用 f 的 Handler。

    source

    type HandlerFunc func(ResponseWriter, *Request)
    
    // ServeHTTP calls f(w, r).
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
        f(w, r)
    }
    

    同样,您可以改用多路复用路由器HandlerFunc

    app.PathPrefix("/").HandlerFunc(serveReact)
    
    func serveReact(w http.ResponseWriter, r *http.Request) {
    }
    

    这实际上是在一个合并的单个步骤中为您执行这两个步骤。

    【讨论】:

    • 我的其他路线与 r.HanddleFunc 一起使用,为什么 PathPrefix 想要如此不同的东西?
    • 那么您使用的是Handler 方法。也许您在其他情况下使用了HandlerFunc 方法? github.com/gorilla/mux/blob/… vs github.com/gorilla/mux/blob/… 我正在更新我的答案,以展示如何避免将其包装在 http.HandlerFunc() 中。
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2013-01-19
    • 2017-12-06
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多