我有一个网站,在本地测试时可以完美运行;然而,当我部署它时,它似乎随机获得不正确/过时的 JSON 数据。这是一个投票应用程序,因此如果选票是 c1、c2、c3 并且我删除了 c3,则 c3 有时会出现,有时不会。在 Firefox Web 开发工具中禁用缓存似乎并不能解决这个问题,ctrl f5 也没有解决这个问题。
我尝试在前端和后端添加带有时间戳的缓存清除功能,并且没有缓存标头。 前端示例
useEffect(() => {
const fetchVotingStatus = async () => {
try {
const response = await fetch(`/get_voting_status?_t=${timestamp}`, {
method: 'GET',
headers: {
'Cache-Control': 'no-cache, no-store',
'Pragma': 'no-cache',
'Expires': '0',
},
})
const data = await response.json();
if (!data.voting_status.President) {
// Voting for President is closed, redirect to the home page
navigate('/');
} else {
// Voting is open, fetch candidates
fetchCandidates();
}
} catch (error) {
console.error('Error fetching voting status:', error);
}
};def add_no_cache_headers(response):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
response.headers['Access-Control-Allow-Origin'] = '*'
return response
@app.after_request
def apply_no_cache(response):
no_cache_routes = [
'no_cache', 'get_voter',
'getJsonVoteStatus', 'handle_submit_vote', 'open_vote', 'close_vote',
'pres_candidates', 'memb_candidates', 'AO_candidates', 'SE_candidates',
'MC_candidates', 'finance_candidates', 'IandB_candidates', 'othervote_prompt',
'othervote_options', 'open_vote', 'close_vote'
]
if request.endpoint in no_cache_routes:
return add_no_cache_headers(response)
return response
后端示例
def add_no_cache_headers(response):
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
response.headers['Access-Control-Allow-Origin'] = '*'
return response
@app.after_request
def apply_no_cache(response):
no_cache_routes = [
'no_cache', 'get_voter',
'getJsonVoteStatus', 'handle_submit_vote', 'open_vote', 'close_vote',
'pres_candidates', 'memb_candidates', 'AO_candidates', 'SE_candidates',
'MC_candidates', 'finance_candidates', 'IandB_candidates', 'othervote_prompt',
'othervote_options', 'open_vote', 'close_vote'
]
if request.endpoint in no_cache_routes:
return add_no_cache_headers(response)
return response
我在后端使用一些全局变量,所以数据可能以某种方式持续存在?我开始怀疑问题是否出在 heroku 上,因为该应用程序在本地运行并提取所有正确的数据
要持久保存数据并保持 Heroku 应用程序的一致性,该应用程序必须有一个 数据存储,例如 Heroku Data for Redis。当 web dyno 重新启动时,应用程序进程中的全局变量以及存储在文件中的数据将被丢弃。如果应用程序运行多个 Web dyno,则没有一种机制可以在正在运行的 Web dyno 之间同步全局变量或临时文件。