我正在尝试使用 Astro 构建一个静态网站,但我想添加一个组件,允许用户通过 HTML 表单注册新闻通讯。按照 Astro 的指南,我使用 API 端点来接受表单数据并处理逻辑。但是,在提交表单时,我在调用
Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded"
时收到错误 await request.formData();
。据我所知,通过查看请求中的标头,它被编码为多部分/表单数据:
Content-Type: multipart/form-data;boundary=---------------------------30448001245691757982165322994
以及有效负载:
-----------------------------30448001245691757982165322994
Content-Disposition: form-data; name="email"
[email protected]
-----------------------------30448001245691757982165322994--
API 端点代码(来自 Astro 文档):
import type { APIRoute } from "astro";
export const POST: APIRoute = async ({ request }) => {
const data = await request.formData(); // error is thrown here
const email = data.get("email");
// Validate the data - you'll probably want to do more than this
if (!email) {
return new Response(
JSON.stringify({
message: 'Missing required fields',
}),
{ status: 400 }
);
}
// Do something with the data, then return a success response
return new Response(
JSON.stringify({
message: "Success!"
}),
{ status: 200 }
);
}
以及发送请求的 JavaScript:
const formData = new FormData(event.currentTarget as HTMLFormElement);
const response = await fetch("/api/newsletter", {
method: "POST",
body: formData,
});
const apidata = await response.json();
问题出在 Astro 预渲染 API 端点上。由于我为
output: hybrid
配置了 Astro,因此我需要明确告诉 Astro 不要预渲染 API 端点。
在 API 端点代码顶部添加
export const prerender = false;
解决了该问题。