feat(跨域): 添加CORS支持以处理OPTIONS请求和响应头

添加跨域资源共享(CORS)支持,包括处理OPTIONS预检请求和在响应头中添加必要的CORS字段
移除不再使用的Cloud-Expiration头
This commit is contained in:
2025-09-05 10:48:09 +08:00
parent 7675a18c91
commit bf7ab1a35c
2 changed files with 19 additions and 3 deletions

View File

@@ -215,6 +215,18 @@ async function tryServeFromStaleCacheOrError(uniqidhex, res, errorMessage) {
}
async function handleMainRequest(req, res) {
// 处理OPTIONS请求支持跨域预检
if (req.method === 'OPTIONS') {
res.writeHead(200, {
'Access-Control-Allow-Origin': req.headers.origin || '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400'
});
res.end();
return;
}
req.url = req.url.replace(/\/{2,}/g, '/');
const parsedUrl = url.parse(req.url, true);
const sign = parsedUrl.query.sign || '';
@@ -426,7 +438,6 @@ const fetchAndServe = async (data, tempCacheContentFile, cacheContentFile, cache
const baseHeaders = {
'Cloud-Type': data.cloudtype,
'Cloud-Expiration': data.expiration,
'ETag': data.uniqid || '',
'Cache-Control': 'public, max-age=31536000', // 1 year
'Expires': new Date(Date.now() + 31536000000).toUTCString(),
@@ -434,6 +445,9 @@ const fetchAndServe = async (data, tempCacheContentFile, cacheContentFile, cache
'Connection': 'keep-alive',
'Date': new Date().toUTCString(),
'Last-Modified': data.headers['last-modified'] || new Date().toUTCString(),
'Access-Control-Allow-Origin': req.headers.origin || '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
const responseHeaders = {
...baseHeaders,
@@ -566,7 +580,6 @@ async function serveFromCache(cacheData, cacheContentFile, cacheMetaFile, res, r
const baseHeaders = {
'Cloud-Type': cacheData.cloudtype || 'unknown',
'Cloud-Expiration': cacheData.expiration || 'N/A',
'ETag': etag || '',
'Cache-Control': 'public, max-age=31536000', // 1 year
'Expires': new Date(Date.now() + 31536000000).toUTCString(),
@@ -574,6 +587,9 @@ async function serveFromCache(cacheData, cacheContentFile, cacheMetaFile, res, r
'Connection': 'keep-alive',
'Date': new Date().toUTCString(),
'Last-Modified': lastModified || new Date().toUTCString(),
'Access-Control-Allow-Origin': req.headers.origin || '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
};
viewsInfo.increment('cacheCall');