SyntaxError: Unexpected end of JSON input on return bodyCache[key] = raw[key]();
Closed this issue · 4 comments
fzn0x commented
What version of Hono are you using?
^4.2.6
What runtime/platform is your app running on?
Bun 1.1.3
What steps can reproduce the bug?
You can try modify request like this to get this error.
import { z } from "zod";
const escapeHtml = (text: string) => {
const map: Record<string, string> = {
"<": "<",
">": ">",
"&": "&",
"'": "'",
'"': """,
"/": "/",
};
return text.replace(/[<>&'"\/]/g, (char: string): string => map[char]);
};
const safeHtmlString = z.string().transform((str) => escapeHtml(str));
export default safeHtmlString;
app.use(async (c, next) => {
const json = await c.req.json();
for (let key in json) {
if (json.hasOwnProperty(key)) {
if (typeof json[key] === "string") {
json[key] = sanitize.parse(json[key]);
}
}
}
// Modify request like hono/validator
c.req.bodyCache.json = json;
await next();
});
What is the expected behavior?
json request modified and no error while running server with Bun.
What do you see instead?
79 | return await new Response(body)key;
80 | })();
81 | }
82 | }
83 |
84 | return bodyCache[key] = rawkey;
^
SyntaxError: Unexpected end of JSON input
Additional information
No response
fzn0x commented
I suspect it related with request.clone()
issue from Bun because it also returns SyntaxError: Unexpected end of JSON input
,
yusukebe commented
Hi @fzn0x
Maybe the body is blank or not a valid JSON string. So, you have to handle the error yourself.
fzn0x commented
Solved thanks!! I think we could improve the message in the future :)
app.use(async (c, next) => {
try {
const json = await c.req.json();
for (let key in json) {
if (json.hasOwnProperty(key)) {
if (typeof json[key] === "string") {
json[key] = sanitize.parse(json[key]);
}
}
}
c.req.bodyCache.json = json;
} catch (_err) {
} finally {
await next();
}
});