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

Svelte服务端表单请求为何收到HTML而非JSON响应?

问题分析与解决

核心错误

你的代码存在关键问题:当设置Content-Type: application/json请求头时,直接将JavaScript对象作为body传递给fetch,但fetch不会自动将对象序列化为JSON字符串。这会导致API接收到[object Object]这类无效内容,无法正确解析,进而返回HTML格式的错误页面(比如400 Bad Request的提示页),最终触发update_res.json()的解析错误。

修正代码

将body参数改为序列化后的JSON字符串:

savechanges: async ({ params, request }) => {
    const data = await request.formData();
    const body = { toggled: data.get("toggled"), channel: data.get("channel"), role: data.get("role") };

    const update_res = await fetch(`https://myapi.com`, {
        method: "POST",
        headers: { auth: API_KEY, "Content-Type": "application/json" },
        body: JSON.stringify(body), // 转为JSON序列化字符串
    });

    // 先检查响应状态,提前捕获错误
    if (!update_res.ok) {
        const errorHtml = await update_res.text();
        console.error("API返回错误页面内容:", errorHtml);
        return { success: false };
    }

    const update = await update_res.json();
    return update ? update : { success: false };
}

额外排查建议

  • 打印update_res.status查看响应状态码,确认是客户端请求错误(4xx)还是服务端错误(5xx)。
  • 在解析JSON前调用update_res.text()查看返回的HTML内容,能直接获取API给出的具体错误提示,进一步定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:30:10