【问题标题】:React Scripts Not Found When Using GoLang http.FileServer使用 GoLang http.FileServer 时未找到 React 脚本
【发布时间】:2017-07-04 18:27:31
【问题描述】:

我正在开发一个 Golang 数据库项目,我想在其中使用 React 创建前端。我正在使用链接到我的 index.html 的反应脚本。

当我直接打开我的 index.html 时,我的反应脚本工作并且页面格式正确。但是,当我尝试通过我的服务器打开页面时,找不到脚本并出现 404 错误:

::1 - - [15/Feb/2017:16:16:24 -0500] "GET /build/react.js HTTP/1.1" 404 19

为了从我的 Golang 服务器访问 index.html,我使用:

r.Handle("/", http.FileServer(http.Dir("./views")))

我认为问题在于使用 http.FileServer 访问 html。我尝试将我的构建文件夹定位在各种位置,最近一次位于视图文件夹中,结果总是相同,直接打开 html 时反应脚本工作,但当我的服务器访问 html 时它们不起作用。

我应该使用另一种方法来完成此任务,还是我组织依赖项的方式有问题?

【问题讨论】:

标签: javascript html reactjs go directory


【解决方案1】:

我通过添加解决了这个问题:

r.PathPrefix("/build/").Handler(http.StripPrefix("/build/", http.FileServer(http.Dir("./build/"))))

在我的主要功能中,以便为反应脚本提供服务。我的文件结构是:

 main.go
 views
 -- index.html (views/index.html)
 build
 -- react.js (build/react.js)
 -- react-dom.js (build/react.js)
 -- other react scripts...

希望这对可能正在处理此问题的其他人有所帮助。

【讨论】:

  • 这与我构建的 react 应用程序发布到 go app 文件夹中的 /public 文件夹的情况略有不同。当 main.go 运行时,所有的 HTTP 请求都被拦截并且没有到达响应页面。这有助于我再次通过反应提出请求stackoverflow.com/questions/64650343/…
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 2014-02-09
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多