【发布时间】:2020-08-14 09:06:43
【问题描述】:
我正在使用 React、Node/Express 和 PostgreSQL 制作音乐播放列表/博客网站。我正在使用 Heroku 进行部署。以下是直播应用的链接:
实时应用: https://earth-nights.herokuapp.com/
当用户点击主页上的“Earth Nights #1”卡片时,用户将被带到该特定播放列表的内容页面 (https://earth-nights.herokuapp.com/episode/1)。很好,但是当我刷新页面时,我只能看到该页面的 API 信息:
{
"id": 1,
"title": "Earth Nights #1",
"date_of_show": "April 24, 2020",
"teaser": "Welcome to the first Earth Nights playlist!",
"card_image": "https://cdn.technologynetworks.com/tn/images/thumbs/jpeg/640_360/the-psychedelic-revolution-in-psychiatry-333007.jpg"
}
我已按照此页面上的说明禁用 Node.js 应用程序的所有缓存:https://devcenter.heroku.com/articles/nodejs-support#cache-behavior,但问题仍然存在。
我在缓存方面做错了什么,或者您可以看到任何其他问题吗?我的服务器代码如下。如果您能提供任何见解,我将不胜感激。
index.js
const express = require('express');
const app = express();
const cors = require('cors');
const pool = require('./db');
const path = require("path");
const PORT = process.env.PORT || 5000;
//middleware
app.use(cors());
app.use(express.json());
app.use(express.static("client/build", {
etag: true, // Just being explicit about the default.
lastModified: true, // Just being explicit about the default.
setHeaders: (res, path) => {
const hashRegExp = new RegExp('\\.[0-9a-f]{8}\\.');
if (path.endsWith('.html')) {
// All of the project's HTML files end in .html
res.setHeader('Cache-Control', 'no-cache');
} else if (hashRegExp.test(path)) {
// If the RegExp matched, then we have a versioned URL.
res.setHeader('Cache-Control', 'max-age=31536000');
}
},
}));
if(process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
}
console.log(__dirname);
console.log(path.join(__dirname, "client/build"));
//routes
//get all episodes
app.get('/episode', async (req, res) => {
try {
const allEpisodes = await pool.query("SELECT * FROM card ORDER BY id DESC");
res.json(allEpisodes.rows);
} catch (err) {
console.error(err.message);
}
});
//select one episode
app.get('/episode/:id', async (req, res) => {
try {
const { id } = req.params;
const episodeContent = await pool.query(
"SELECT * FROM card WHERE id = $1", [
id
]);
res.json(episodeContent.rows[0])
} catch (err) {
console.error(err.message)
}
});
app.get('/episode/:id/playlist', async (req, res) => {
try {
const { id } = req.params;
const episodeContent = await pool.query(
"SELECT * FROM playlist WHERE episode = $1", [
id
]);
res.json(episodeContent.rows)
} catch (err) {
console.error(err.message)
}
});
app.post("/send", async (req, res) => {
try {
const { name, email, message } = req.body;
const newMessage = await pool.query(
"INSERT INTO messages (name, email, message) VALUES ($1, $2, $3) RETURNING *", [
name,
email,
message
]
);
res.json(newMessage.rows[0]);
} catch (err) {
console.error(err.message)
}
});
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`server has started on http://localhost:${PORT}`);
});
【问题讨论】: