首页 > 解决方案 > 为什么我的静态网页会出现 404?

问题描述

我已经工作了大约 2 年来开发全栈应用程序(当我最初接触它们时这些应用程序已经相当成熟了)并且我正在从头开始我的第一个应用程序。我花了一天时间创建一个 EC2 实例,为我的堆栈加载依赖项(Postgres、golang、react),以及一台闪亮的新机器所需的所有其他装饰(tmux、npm、vim 插件、git 集成等)。我现在卡住了。我使用 create-react-app 开始我的前端并运行 npm start 进行构建。要看到这个,我可以去我的 instanceip:3000。我创建了在 8080 端口上提供服务的 golang 服务器代码,我可以通过访问 instanceip:8080/hello 来访问我的 helloworld 代码。我在我的反应代码中添加了一个 axios 调用来获取返回 404 的端点 /hello。

我还尝试让我的 golang 将 index.js 作为 instanceip:8080 的静态页面处理,并返回 404。

我如何让我的不同端口玩得很好?我无法弄清楚我在这里缺少什么。

这是我的主要服务器代码片段:

indexLoc := os.Genenv(webRootEnv) + "/index.html" // verified this is the correct path to my static index.html file by logging it out
fs := http.FileServer(http.Dir(indexLoc))
http.ListenAndServe(":8080", nil)
http.Handle("/", fs)

有人知道我缺少什么吗?提前致谢!

标签: amazon-web-servicesgoserver

解决方案


有两件事可能是原因:

  • 您正在为 提供一个文件名http.Dir,它需要一个目录。
  • 您的处理程序在调用后注册ListenAndServe,因此使其无用(永远不会调用 http.Handle)

您可以通过像这样更改代码来修复它:

indexLoc := os.Genenv(webRootEnv) // webRootEnv is a directory path
fs := http.FileServer(http.Dir(indexLoc))
http.Handle("/", fs) // register handler before listening
http.ListenAndServe(":8080", nil)

您可能还想处理返回的错误,ListenAndServe以防止程序静默失败


推荐阅读