feat(跨域): 添加CORS支持以处理OPTIONS请求和响应头
添加跨域资源共享(CORS)支持,包括处理OPTIONS预检请求和在响应头中添加必要的CORS字段 移除不再使用的Cloud-Expiration头
This commit is contained in:
20
source.js
20
source.js
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user