Netlify 在页面刷新时呈现 404(使用 React 和 react-router)

Jen*_*nna 34 http-status-code-404 reactjs react-router netlify

我已经使用 Netlify 部署了我的站点,但在路由方面遇到了问题。

这是我的网站:https : //redux-co.netlify.com/

还有我的 GitHub 仓库:https : //github.com/jenna-m/redux-co

具体来说,如果用户导航到主页以外的任何页面并刷新页面,则默认 Netlify 404 呈现。从 404 页面,如果我导航回主页并刷新,则呈现主页。

此外,我的自定义 404 页面无法像我打开时那样工作localhost:3000,但我想在处理我的自定义 404 组件之前先弄清楚这个刷新问题。

我正在使用 React 和 react-router,我知道由于我使用的是 react-router,我的网站不会立即部署。


这是我的_redirects文件,它在/public我的index.html文件所在的文件夹中:

/*    /index.html   200
Run Code Online (Sandbox Code Playgroud)

这是我“build”位于package.json

…
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build && cp build/index.html build/404.html",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
…
Run Code Online (Sandbox Code Playgroud)

我读过其他人遇到过这种情况以及他们为克服这个问题所做的工作。这是我到目前为止所引用的……

https://www.freecodecamp.org/news/how-to-deploy-a-react-application-to-netlify-363b8a98a985/

https://hugogiraudel.com/2017/05/13/using-create-react-app-on-netlify/

这个人使用的是 Vue 而不是 React,但我还是尝试了这些解决方案:

https://github.com/vuejs/vuepress/issues/457#issuecomment-390206649

https://github.com/vuejs/vuepress/issues/457#issuecomment-463745656

man*_*kin 63

这很简单,对我有用。我找到了这个链接https://create-react-app.dev/docs/deployment#netlify

因此,按照该链接的建议,我在_redirects文件/public夹中添加了一个文件,例如/public/_redirects. 然后我粘贴/* /index.html 200_redirects文件中。我在我的 VS Code 中完成了所有这些,之后我推送到 github,然后每次推送到 github 时我的 netlify 都会自动重新部署。我的问题解决了,刷新不再带来 404 错误。

在我的 package.json 中,构建部分如下所示;

"scripts": {
   "start": "react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test",
   "eject": "react-scripts eject"
}
Run Code Online (Sandbox Code Playgroud)

注意: 有些文章说您需要添加_redirectsbuild文件夹中,但是在我的情况下,构建文件夹不在推送到 github 的内容中,所以这就是为什么添加_redirectspublic文件夹对我来说效果更好,因为公共文件夹可以与我的代码。


Moh*_*nji 11

netlify.toml文件添加到项目的根目录并粘贴以下代码:

[[redirects]]
  from = "/*"
  to = "/"
  status = 200
Run Code Online (Sandbox Code Playgroud)

推送并重新部署您的应用程序就完成了。


Om *_*uke 11

我遇到了类似的问题,因此我在公共文件夹中创建了_redirects文件并放置以下代码

/* /index.html 200
Run Code Online (Sandbox Code Playgroud)

再次构建文件npm run build 并为我解决 类似问题的资源


小智 10

_redirects从您的公共文件夹中删除并移动netlify.toml到您的 git 存储库的根目录,更多信息。也从构建脚本中删除&& cp build/index.html build/404.html- 你不再需要它了

  • 我在 netlify.toml 中添加了它并且它有效!`[[重定向]] 从 = "/*" 到 = "/index.html" status = 200` (3认同)