我的前端和后端代码托管在 Cyclic.sh 上,并且该网站运行良好,除非刷新页面并且我不在主页上。此处刷新“website-name.cycling.app/”有效,但不适用于“website-name.cycling.app/any-other-route”。 我相信这是由于React的客户端路由和我的后端无法在页面刷新时从index.html文件进入。
我的前端有一个 dist 文件夹,其中保存了我的生产代码,并且在后端代码的 server.js 文件中,我已添加了此文件夹,按照 Cyclic 关于部署静态站点的文档:
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html', 'css', 'js', 'ico', 'jpg', 'jpeg', 'png', 'svg'],
index: ['index.html'],
maxAge: '1m',
redirect: false,
};
// Serve static files from the 'dist' directory.
app.use(express.static('dist', options));
但这并不能解决问题。我在这里做错了什么?
编辑
我已将我的代码更新为 server.js 文件底部的类似内容,但仍然没有成功。
// Serve static files from the 'dist' directory.
app.use(express.static('dist'));
app.get('*', (req, res, next) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
connectDB().then(() => {
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`);
});
});
你可以尝试一下吗
const fs = require('fs')
// your other code
app.use(express.static('dist'));
// All your other routes here
app.get('*', (req, res, next) => {
const content = fs.readFileSync(path.resolve(__dirname, 'dist', 'index.html'), 'utf-8')
res.send(content);
});
connectDB().then(() => {
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`);
});
});