SvelteKit中+page.server.js返回空值引发JSON解析错误求助
注册功能JSON解析错误排查与解决
问题描述
之前项目中使用下述代码实现用户注册功能运行正常,但在新项目中出现错误:Uncaught (in promise) SyntaxError: Unexpected end of JSON input。经排查,数据库可成功添加新用户,但疑似+page.server.js返回空字符串导致前端JSON解析失败,寻求解决建议。
相关代码
+page.svelte
<script> import { send } from '$lib/api'; export let error; export let success; async function register(event) { error = ''; const formEl = event.target; const response = await send(formEl); if (response.error) { error = response.error; } if (response.success) { success = response.success; } formEl.reset(); } </script> <form on:submit|preventDefault={register} method="post" autocomplete="off"> ...... </form>
api.js
export async function send(form) { const response = await fetch(form.action, { method: form.method, body: new FormData(form), headers: { accept: 'application/json' }, }); return await response.json(); }
+page.server.js
import * as bcrypt from 'bcrypt'; import { db } from '$lib/database'; export const POST = async ({ request }) => { const form = await request.formData(); const username = form.get('username').trim(); const password = form.get('password').trim(); if (typeof username !== 'string' || typeof password !== 'string') { return { status: 400, body: { error: 'Something went horribly wrong.', }, }; } if (!username || !password) { return { status: 400, body: { error: 'Username and password is required.', }, }; } try { await db.user.create({ data: { username, passwordHash: await bcrypt.hash(password, 10), }, }); return { status: 200, body: { success: 'Success.' } }; } catch (error) { return { status: 400, body: { error: 'User already exists.', }, }; } };
解决建议
1. 适配SvelteKit响应格式要求
新版SvelteKit不再支持server端路由直接返回{ status, body }对象,需用官方提供的json()辅助函数或手动构造Response对象:
方法一:使用json()辅助函数(推荐)
导入json并修改所有返回语句:
import { json } from '@sveltejs/kit'; // ...其他代码 // 非法参数场景 return json({ error: 'Something went horribly wrong.' }, { status: 400 }); // 空字段场景 return json({ error: 'Username and password is required.' }, { status: 400 }); // 注册成功场景 return json({ success: 'Success.' }, { status: 200 }); // 用户名已存在场景 return json({ error: 'User already exists.' }, { status: 400 });
方法二:手动构造Response对象
// 注册成功示例 return new Response(JSON.stringify({ success: 'Success.' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); // 错误场景示例 return new Response(JSON.stringify({ error: 'Username and password is required.' }), { status: 400, headers: { 'Content-Type': 'application/json' } });
2. 调试响应内容
在api.js中临时添加调试代码,确认后端实际返回的内容:
export async function send(form) { const response = await fetch(form.action, { method: form.method, body: new FormData(form), headers: { accept: 'application/json' }, }); // 打印原始响应内容 const rawText = await response.text(); console.log('Server response:', rawText); try { return JSON.parse(rawText); } catch (err) { console.error('JSON parse failed:', err); return { error: '服务器响应格式错误' }; } }
3. 检查响应头一致性
确保后端返回的响应头包含Content-Type: application/json,否则即使返回正确的JSON字符串,前端也可能无法正确解析。
4. 确认代码执行路径
在+page.server.js的try块中添加日志,确认代码确实执行到了返回语句:
try { await db.user.create({ data: { username, passwordHash: await bcrypt.hash(password, 10), }, }); console.log('User created, returning success response'); // 添加此行日志 return json({ success: 'Success.' }, { status: 200 }); } catch (error) { console.log('Error creating user:', error); return json({ error: 'User already exists.' }, { status: 400 }); }
内容的提问来源于stack exchange,提问作者Williamz
相关产品推荐
相关产品推荐

