106 lines
2.6 KiB
JavaScript
106 lines
2.6 KiB
JavaScript
export async function onRequestPost(context) {
|
|
try {
|
|
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',
|
|
'Access-Control-Allow-Origin': '*'
|
|
}
|
|
}
|
|
);
|
|
}
|
|
|
|
// Send email using Resend
|
|
const response = await fetch('https://api.resend.com/emails', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': `Bearer ${context.env.RESEND_API_KEY}`,
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({
|
|
from: 'contact@argobox.com',
|
|
to: 'daniel.laforce@gmail.com',
|
|
subject: `Contact Form: ${subject}`,
|
|
html: `
|
|
<h3>New Contact Form Submission</h3>
|
|
<p><strong>Name:</strong> ${name}</p>
|
|
<p><strong>Email:</strong> ${email}</p>
|
|
<p><strong>Subject:</strong> ${subject}</p>
|
|
<h4>Message:</h4>
|
|
<p>${message}</p>
|
|
`
|
|
})
|
|
});
|
|
|
|
const responseData = await response.json();
|
|
|
|
if (!response.ok) {
|
|
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',
|
|
'Access-Control-Allow-Origin': '*'
|
|
}
|
|
}
|
|
);
|
|
} catch (error) {
|
|
console.error('Server error:', error);
|
|
return new Response(
|
|
JSON.stringify({
|
|
error: 'An unexpected error occurred'
|
|
}),
|
|
{
|
|
status: 500,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*'
|
|
}
|
|
}
|
|
);
|
|
}
|
|
}
|