我正在尝试使用 Nuxt3 $fetch 服务器端写入数据库。我正在使用 prisma 访问数据库。当我使用 $fetch 时,我希望端点将“成功”字符串返回到我的组件,以便我可以在 UI 上将其呈现给用户。当我尝试控制台日志answer来检查它是否“成功”时,它是未定义的。我是否没有在 API 中正确返回,或者我应该使用不同的函数,例如 useFetch?
组件功能:
async pushToDatabase() {
for (const row of this.information) {
if (row.data.firstName != "" && row.data.lastName != "") {
const { answer } = await $fetch("/api/addRow", {
method: "POST",
body: row,
});
console.log(answer);
}
}
},
API 处理程序:
export default defineEventHandler(async (event) => {
const body = await readBody(event);
const info = body.data as IAttendeeData;
console.log(body);
await prisma.test
.create({
data: {
firstName: info.firstName,
lastName: info.lastName,
age: info.age,
gender: info.gender,
},
})
.then(() => {
console.log("write worked");
return "success";
})
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.catch((err) => {
console.log(err.message);
console.log("failed write");
});
});
您正在破坏对属性的响应
anwser
。您确定您的回复包含此类数据吗?尝试显示完整的回复:
const response = await $fetch("/api/addRow", {
method: "POST",
body: row,
});
console.log(response );