You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit中如何用Prisma获取新创建帖子的ID?

解决SvelteKit创建帖子后获取返回ID的问题

服务器端代码修正

你当前的服务器端函数存在两个问题:一是错误地传入了response参数(SvelteKit的RequestHandler参数中没有这个字段),二是返回了无效的response对象而非创建好的帖子数据。修改后代码如下:

/** @type {import('./$types').RequestHandler} */
export async function POST({ request }) {
    const { author, comment, area_id, date, shift, ip } = await request.json();
    const createdPost = await prisma.TurnReport.create({
        data: {
            comment: comment,
            datetime: new Date().toISOString(),
            author: author,
            area_id: area_id,
            shift_date: date,
            shift_num: shift,
            ip: ip,
        }
    })
    // 返回完整的新帖子数据,包含ID
    return json(createdPost);
    // 若仅需返回ID,可替换为:return json({ id: createdPost.id });
}

客户端代码修正

你当前只是打印了response对象本身,但没有解析响应体内的JSON数据。需要调用response.json()来提取服务器返回的内容,才能拿到帖子ID:

const response = await fetch('/api/comment', {
    method: 'POST',
    body: JSON.stringify({ author, comment, area_id, date, shift, ip }),
    headers: {
        'content-type': 'application/json'
    }
})
if (response.ok) {
    console.log('Message Sent successfully!');
    // 解析服务器返回的JSON数据
    const newPost = await response.json();
    // 获取新帖子的ID
    console.log('新帖子ID:', newPost.id);
} else {
    console.log('Try agian...punk!');
}

关键说明

  • 服务器端通过json()方法将创建后的帖子对象(或仅ID)返回给客户端
  • 客户端必须调用response.json()解析响应体,才能访问到返回的ID字段

内容的提问来源于stack exchange,提问作者Avi4nFLu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 03:35:18