修复浏览器缓存导致前端没更新的问题

This commit is contained in:
John Smith 2023-07-29 23:05:04 +08:00
parent 6d5232d7d8
commit ecb4a08e56
4 changed files with 27 additions and 8 deletions

View File

@ -108,6 +108,8 @@ server {
ssl_certificate /PATH/TO/CERT.crt;
ssl_certificate_key /PATH/TO/CERT_KEY.key;
set $blivechat_path /PATH/TO/BLIVECHAT;
client_body_buffer_size 256k;
client_max_body_size 1.1m;
@ -120,12 +122,20 @@ server {
# 静态文件
location / {
root /PATH/TO/BLIVECHAT/frontend/dist;
# 如果文件不存在,交给前端路由
try_files $uri $uri/ /index.html;
root $blivechat_path/frontend/dist;
try_files $uri $uri/ @index;
}
# 不存在的文件请求转发到index.html交给前端路由
location @index {
rewrite ^ /index.html last;
}
location = /index.html {
root $blivechat_path/frontend/dist;
# index.html不缓存防止更新后前端还是旧版
add_header Cache-Control no-cache;
}
location /emoticons {
alias /PATH/TO/BLIVECHAT/data/emoticons;
alias $blivechat_path/data/emoticons;
}
# 动态API
location /api {

View File

@ -10,6 +10,8 @@ class ApiHandler(tornado.web.RequestHandler): # noqa
self.json_args = None
def prepare(self):
self.set_header('Cache-Control', 'no-cache')
if not self.request.headers.get('Content-Type', '').startswith('application/json'):
return
try:

View File

@ -19,13 +19,22 @@ EMOTICON_BASE_URL = '/emoticons'
class MainHandler(tornado.web.StaticFileHandler): # noqa
"""为了使用Vue Router的history模式把不存在的文件请求转发到index.html"""
async def get(self, path, include_body=True):
if path == '':
await self._get_index(include_body)
return
try:
await super().get(path, include_body)
except tornado.web.HTTPError as e:
if e.status_code != 404:
raise
# 不存在的文件请求转发到index.html交给前端路由
await super().get('index.html', include_body)
await self._get_index(include_body)
async def _get_index(self, include_body=True):
# index.html不缓存防止更新后前端还是旧版
self.set_header('Cache-Control', 'no-cache')
await super().get('index.html', include_body)
class ServerInfoHandler(api.base.ApiHandler): # noqa

View File

@ -29,7 +29,7 @@ routes = [
(r'/api/avatar_url', api.chat.AvatarHandler),
(rf'{api.main.EMOTICON_BASE_URL}/(.*)', tornado.web.StaticFileHandler, {'path': api.main.EMOTICON_UPLOAD_PATH}),
(r'/(.*)', api.main.MainHandler, {'path': config.WEB_ROOT, 'default_filename': 'index.html'})
(r'/(.*)', api.main.MainHandler, {'path': config.WEB_ROOT})
]
@ -98,8 +98,6 @@ def run_server(host, port, debug):
return
finally:
url = 'http://localhost/' if port == 80 else f'http://localhost:{port}/'
# 防止更新版本后浏览器加载缓存
url += '?_v=' + update.VERSION
webbrowser.open(url)
logger.info('Server started: %s:%d', host, port)
tornado.ioloop.IOLoop.current().start()