SvelteKit服务端端点无法向FormSubmit发送表单数据
问题
开发SvelteKit项目时,尝试从服务端端点(+page.server.ts)向FormSubmit.co的AJAX接口发送表单数据失败,但客户端(+page.svelte)直接发送可成功。部署到Vercel后问题依旧,收到错误:
{
success: "false",
message: "Make sure you open this page through a web server, FormSubmit will not work in pages browsed as HTML files."
}
服务端代码(+page.server.ts)
export const actions = { default: async ({ request }) => { const formData = await request.formData(); const formValues = Object.fromEntries(formData); // ... 其他逻辑 const response = await fetch('https://formsubmit.co/ajax/your-formsubmit-id', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(formValues) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); if (data.success === 'false') { throw new Error(data.message); } return { status: 200, body: { success: true, resultMessage: 'The message was sent correctly' } }; } };
客户端表单代码(+page.svelte)
... <form action="#" method="POST" use:enhance={() => { isLoading = true; return async ({ update }) => { await update(); isLoading = false; }; }} class="mx-auto mt-10 max-w-xl sm:mt-15" > ...
解决方案
FormSubmit的AJAX接口会检查请求的Referer或Origin头,服务端发起请求时默认没有这些头,导致接口误判请求来自本地文件而非Web服务器。
方法1:添加Referer头
修改服务端的fetch请求,添加对应你网站域名的Referer头:
const response = await fetch('https://formsubmit.co/ajax/your-formsubmit-id', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'Referer': 'https://your-vercel-domain.vercel.app' // 替换为你的实际域名,本地开发用http://localhost:5173 }, body: JSON.stringify(formValues) });
方法2:直接发送FormData(推荐)
客户端请求默认用multipart/form-data格式发送FormData,服务端之前转成JSON的方式可能不符合FormSubmit的预期,直接传递原始FormData:
// 无需将formData转成普通对象 const response = await fetch('https://formsubmit.co/ajax/your-formsubmit-id', { method: 'POST', headers: { Accept: 'application/json', 'Referer': 'https://your-vercel-domain.vercel.app' // 替换为实际域名 }, body: formData // 直接传递FormData对象 });
内容的提问来源于stack exchange,提问作者Matteo Trupia
相关产品推荐
相关产品推荐

