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

SvelteKit POST请求端点问题:SQL执行时question和answer未定义

解决建议

1. 修复前端参数传递错误

你的+page.svelte里的add函数参数是context,但在JSON.stringify里使用了未定义的question变量,导致前端发送的请求体里question字段不存在或为undefined。

修改方式二选一:

  • 直接将context赋值给question字段:
async function add(context: string, answer: string) {
    console.log("cON")
    console.log(context)
    const response = await fetch('/api/searches/add', {
        method: 'POST',
        body: JSON.stringify({ question: context, answer }),
        headers: {
            'content-type': 'application/json'
        }
    });
}
  • 或者把函数参数名从context改为question,利用对象字面量简写:
async function add(question: string, answer: string) {
    console.log("cON")
    console.log(question)
    const response = await fetch('/api/searches/add', {
        method: 'POST',
        body: JSON.stringify({ question, answer }),
        headers: {
            'content-type': 'application/json'
        }
    });
}

2. 修复SQL关键字冲突问题

order是SQL的保留关键字,直接作为列名使用会导致语法错误,可能被误判为参数未定义问题。需要用反引号(MySQL)或双引号(PostgreSQL)包裹该列名:

修改+server.ts中的SQL语句:

let test = await sql`
    insert into users
    (name, slug, question, answer, approved, \`order\` )
    values
    ('name', 'slug', ${ question }, ${ answer }, 0, 0)
    returning name, slug, question, answer, approved, \`order\`
`

注意:如果使用PostgreSQL,需将反引号替换为双引号:"order"

3. 验证参数接收情况

在后端POST函数里添加日志,确认是否正确接收到参数:

export async function POST({ request }) {
    console.log("REQ");
    const { question, answer } = await request.json();
    console.log("Received params:", question, answer);
    // ... 后续代码
}

如果日志显示参数为undefined,说明前端传递仍然有问题,需再检查请求体格式。

内容的提问来源于stack exchange,提问作者Cult of Tranquility

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:12:52