我有以下代码来为Reaction构建应用程序提供服务:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func main() {

    r := http.NewServeMux()

    r.HandleFunc(`^/`, index)
    buildHandler := http.FileServer(http.Dir("build"))
    r.Handle("/", buildHandler)

    srv := &http.Server{
        Handler:      r,
        Addr:         ":5000",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    fmt.Println("Server started on PORT 5000")
    log.Fatal(srv.ListenAndServe())

}

func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "build/index.html")
}

文件夹 struct 如下所示:

enter image description here

但在刷新或try 直接转到PATH时,未找到404.我怎么才能让它go 到想要的路径,而不是go 404?

推荐答案

您遇到的问题与Reaction(或其他前端框架)使用的客户端路由有关.当您刷新页面或直接访问特定路径时,服务器无法识别该路由,因为它主要提供静态index.html文件,而不处理客户端路由.

要解决此问题,您需要将GO服务器配置为通过将所有请求重定向到index.html文件来处理客户端路由.这样,您的Reaction应用程序中的客户端路由就可以接管并处理正确的页面显示.

以下是处理客户端路由的修改代码:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func main() {
    r := http.NewServeMux()

    // Redirect all requests to the index.html file
    r.HandleFunc("/", index)

    // Serve the static files from the "build" directory
    buildHandler := http.FileServer(http.Dir("build"))
    r.Handle("/static/", buildHandler)
    r.Handle("/js/", buildHandler)
    r.Handle("/css/", buildHandler)

    srv := &http.Server{
        Handler:      r,
        Addr:         ":5000",
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    fmt.Println("Server started on PORT 5000")
    log.Fatal(srv.ListenAndServe())
}

func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "build/index.html")
}

在修改后的代码中,我们通过将请求重定向到index.html文件来处理对根路径("/")的请求.此外,我们使用HTTP.FileServer提供"Build"目录中的静态文件(JS、css等).通过这样做,您的服务器将正确地为所有路由提供index.html文件,并且您的Reaction应用程序中的客户端路由将负责显示适当的页面.

Reactjs相关问答推荐

MUImaterial -ui-如何将文本字段和 Select 分组?

在一个地方调用函数会影响其他地方调用该函数

将动态元素中的输入数据传输到Reaction

在Map()完成React.js中的多个垃圾API请求后执行函数

Redux工具包-useSelector如何通过Reducer引用InitialState?

如何使ionic 面包屑在州政府条件下可点击?

如何删除 bootstrap 手风琴上的边框

从 MongoDB createAt 字段中分割精确时间

如何将 npm 包添加到我的 Vite + React 应用程序中?

React Native - 如何处理错误带有有效负载的NAVIGATE操作..未被任何导航器处理?

Next.js 和理智 | npm run build 时预渲染页面/时发生错误

文本的几个词具有线性渐变 colored颜色 - React native

损坏的图像 React useState

当 React 中的状态发生变化时如何停止重新加载谷歌 map ?

如何在 ReactJS 中提交后删除 URL 中的查询参数

使用 Vite 的 React 中的路由无法正常工作(构建中)

使用 React.lazy 调试 webpack 代码拆分

在表格中显示具有自定义声明的用户状态

在 Redux 中更新布尔状态时出错

a.active 类在导入 x.scss 文件时有效,但在使用 x.module.scss 时无效