Skip to content

Commit

Permalink
fix: cors when making a request
Browse files Browse the repository at this point in the history
  • Loading branch information
ephraimduncan committed Jun 17, 2024
1 parent 53b7e16 commit c730bd0
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions apps/web/src/app/api/s/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { userAgent } from 'next/server';

import { type Form } from '@formbase/db/schema';
import { env } from '@formbase/env';

import { sendMail } from '~/lib/email/mailer';
import { renderNewSubmissionEmail } from '~/lib/email/templates/new-submission';
Expand All @@ -9,6 +10,12 @@ import { assignFileOrImage, uploadFileFromBlob } from '~/lib/upload-file';

type Json = string | number | boolean | null | { [key: string]: Json } | Json[];

const CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};

async function getFormData(request: Request): Promise<{
data: Record<string, Blob | string | undefined>;
source: 'formData' | 'json';
Expand Down Expand Up @@ -80,7 +87,12 @@ export async function POST(
const formId = params.id;
const form = await api.form.getFormById({ formId });
if (!form) {
return new Response('Form not found', { status: 404 });
return new Response('Form not found', {
status: 404,
headers: {
...CORS_HEADERS,
},
});
}

const { data: formData, source } = await getFormData(request);
Expand Down Expand Up @@ -111,19 +123,37 @@ export async function POST(
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' },
headers: { 'Content-Type': 'application/json', ...CORS_HEADERS },
},
);
}

return new Response(null, {
status: 303,
headers: { Location: `http://localhost:3000/s/${formId}` },
headers: {
Location: `${env.NEXT_PUBLIC_APP_URL}/s/${formId}`,
...CORS_HEADERS,
},
});
} catch (error) {
console.error(error);
return new Response('There was an issue processing your form', {
status: 500,
headers: {
...CORS_HEADERS,
},
});
}
}

// eslint-disable-next-line @typescript-eslint/require-await
export async function OPTIONS() {
return new Response('', {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}

0 comments on commit c730bd0

Please sign in to comment.