diff --git a/functions/contact.js b/functions/contact.js index 6061a19..72215a9 100644 --- a/functions/contact.js +++ b/functions/contact.js @@ -1,12 +1,38 @@ export async function onRequestPost(context) { try { - const { name, email, subject, message } = await context.request.json(); + let requestData; + try { + requestData = await context.request.json(); + } catch (parseError) { + return new Response( + JSON.stringify({ + error: 'Invalid request data - please provide valid JSON' + }), + { + status: 400, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*' + } + } + ); + } + + const { name, email, subject, message } = requestData; // Validate inputs if (!name || !email || !subject || !message) { return new Response( - JSON.stringify({ error: 'All fields are required' }), - { status: 400, headers: { 'Content-Type': 'application/json' } } + JSON.stringify({ + error: 'All fields are required' + }), + { + status: 400, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*' + } + } ); } @@ -32,18 +58,49 @@ export async function onRequestPost(context) { }) }); + const responseData = await response.json(); + if (!response.ok) { - throw new Error('Failed to send email'); + console.error('Resend API error:', responseData); + return new Response( + JSON.stringify({ + error: 'Failed to send email' + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*' + } + } + ); } return new Response( - JSON.stringify({ message: 'Message sent successfully!' }), - { status: 200, headers: { 'Content-Type': 'application/json' } } + JSON.stringify({ + message: 'Message sent successfully!' + }), + { + status: 200, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*' + } + } ); } catch (error) { + console.error('Server error:', error); return new Response( - JSON.stringify({ error: 'Failed to send message' }), - { status: 500, headers: { 'Content-Type': 'application/json' } } + JSON.stringify({ + error: 'An unexpected error occurred' + }), + { + status: 500, + headers: { + 'Content-Type': 'application/json', + 'Access-Control-Allow-Origin': '*' + } + } ); } } \ No newline at end of file diff --git a/script.js b/script.js index 6facbe4..1aad01f 100644 --- a/script.js +++ b/script.js @@ -149,9 +149,17 @@ if (contactForm) { body: JSON.stringify(data) }); + let responseData; + const responseText = await response.text(); + try { + responseData = JSON.parse(responseText); + } catch (parseError) { + console.error('Failed to parse response:', responseText); + throw new Error('Invalid server response'); + } + if (!response.ok) { - const errorData = await response.json(); - throw new Error(errorData.error || 'Failed to send email'); + throw new Error(responseData.error || 'Failed to send email'); } // Show success message