错误与代码库有关(我使用
monorepo
且 vercel.json
位于根目录中。将 vercel.js
移动到 react
应用程序打包后,一切工作正常。
我有一个简单的
React.js
应用程序,带有基于 wouter
的路由和 Vercel
部署,这让我遇到了一个小问题,我不知道解决方案。刷新(子页面)后它总是返回 404
。
我的代码看起来有点像这样。
<>
<Route path='/' component={Intro} />
<Route path='/dashboard' component={Dashboard} />
</>
在
<Intro />
上我有<Link />
到/dashboard
,这应该将我转移到<Dashboard />
页面。它确实可以在我的本地计算机、容器中以及基于 Linux 的部署上运行,但在 vercel
部署中却不起作用,即使我尝试通过 vercel.json
的配置来解决此问题。
{
"github": {
"silent": true
},
"rewrites": [
{
"source": "(.*)",
"destination": "/index.html"
}
]
}
还尝试了
rewrites
的替代版本,但仍然是同样的问题。
{
"rewrites": [{ "source": "/(.*)", "destination": "/" }]
}
此处提供实时部署的链接:pointrest-6ttd9zep8-araclx.vercel.app
注意:我也尝试使用
但存在同样的问题。当应用程序托管在react-router
上时,存在同样的问题,但当托管在netlify
上或在heroku
容器内运行时,根本不存在。docker
您可以在服务中创建简单的重写规则。就我而言,我使用 Vercel。然后你就可以找到类似的东西。
在项目根目录中创建文件 vercel.json
还有作家
{
"rewrites": [{ "source": "/(.*)", "destination": "/" }]
}
P.S.:不要忘记在 vercel 中启用重写。
TLDR
在public文件夹中添加一个空的404.html(可以将标题放在标题标签中),并在head部分使用此脚本
<script type="text/javascript">
var pathSegmentsToKeep = 0;
var l = window.location;
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash
);
</script>
然后将此脚本添加到您的index.html
<script type="text/javascript">
(function(l) {
if (l.search[1] === '/' ) {
var decoded = l.search.slice(1).split('&').map(function(s) {
return s.replace(/~and~/g, '&')
}).join('?');
window.history.replaceState(null, null,
l.pathname.slice(0, -1) + decoded + l.hash
);
}
}(window.location))
</script>
将我的应用程序部署到 render.com 后,这对我来说非常有效
要处理“真实的”未找到响应,您可以添加此路由
<Route path="*" element={<p>Page not found</p>} />
有关更多信息,您可以访问此存储库spa-github-pages
TL;博士
对于单一存储库配置
vercel.json
应包含在 $ROOT/$PROJECT/vercel.json
下,而不是 $ROOT/vercel.json
。
$ROOT/$PROJECT/vercel.json
{
"github": {
"silent": true
},
"rewrites": [
{
"source": "(.*)",
"destination": "/index.html"
}
]
}
vercel.json
中的配置在添加到问题时是正确的,该问题不存在于单包存储库的项目配置中,其中根目录中的
vercel.json
沿
package.json
。然而,使用单一存储库方法,相同的配置具有与预期不同的行为(如单包存储库中的行为) - 此类问题的解决方案是将
vercel.json
移动到包含
package.json
的存储库的 Project Directory(表示工作空间的目录,相反,它指示给定的 React.js 项目)。