Add CORS headers to fix 403

This commit is contained in:
Web-serfer 2026-04-27 20:55:33 +05:00
parent 7365ff107c
commit 4f6d82bc7b
2 changed files with 37 additions and 17 deletions

View file

@ -39,27 +39,39 @@ async function pbRequest(method: string, path: string, body?: object) {
return JSON.parse(err) || {};
}
function jsonResponse(data: object, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }
});
}
export const POST: APIRoute = async ({ request, url }) => {
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
});
}
console.log('[Increment Views] PB_URL:', POCKETBASE_URL);
try {
const postId = url.searchParams.get('postId');
if (!postId || !POCKETBASE_ID_REGEX.test(postId)) {
return new Response(
JSON.stringify({ error: 'Некорректный postId' }),
{ status: 400, headers: { 'Content-Type': 'application/json' } }
);
return jsonResponse({ error: 'Некорректный postId' }, 400);
}
let post;
try {
post = await pbRequest('GET', `/api/collections/posts/records/${postId}`);
} catch {
return new Response(
JSON.stringify({ error: 'Пост не найден' }),
{ status: 404, headers: { 'Content-Type': 'application/json' } }
);
return jsonResponse({ error: 'Пост не найден' }, 404);
}
const ip = getClientIp(request);
@ -107,16 +119,10 @@ export const POST: APIRoute = async ({ request, url }) => {
}
}
return new Response(
JSON.stringify({ views: totalViews, isNewView }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
);
return jsonResponse({ views: totalViews, isNewView }, 200);
} catch (error) {
console.error('[Increment Views] Error:', error);
return new Response(
JSON.stringify({ error: 'Внутренняя ошибка сервера' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } }
);
return jsonResponse({ error: 'Внутренняя ошибка сервера' }, 500);
}
};

View file

@ -1,6 +1,17 @@
import type { APIRoute } from 'astro';
export const POST: APIRoute = async ({ request, url }) => {
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
});
}
const params = Object.fromEntries(url.searchParams.entries());
return new Response(JSON.stringify({
@ -9,6 +20,9 @@ export const POST: APIRoute = async ({ request, url }) => {
url: request.url,
}), {
status: 200,
headers: { 'Content-Type': 'application/json' }
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
});
};