diff --git a/src/components/Preview.vue b/src/components/Preview.vue index cf8f081..9dae7e9 100644 --- a/src/components/Preview.vue +++ b/src/components/Preview.vue @@ -125,11 +125,29 @@ const submitRequest = async () => { if (url.value) { switch (method.value) { case 'POST': { - highlightCode(await create(url.value, JSON.stringify(exampleRequestBody.value))) + highlightCode( + await create( + url.value, + (() => { + const rawBody = exampleRequestBody.value + const maybeBody = typeof rawBody === 'string' ? rawBody.trim() : rawBody + return maybeBody ? maybeBody : undefined + })() + ) + ) break } case 'PUT': { - highlightCode(await update(url.value, JSON.stringify(exampleRequestBody.value))) + highlightCode( + await update( + url.value, + (() => { + const rawBody = exampleRequestBody.value + const maybeBody = typeof rawBody === 'string' ? rawBody.trim() : rawBody + return maybeBody ? maybeBody : undefined + })() + ) + ) break } case 'DELETE': { diff --git a/src/obp/index.ts b/src/obp/index.ts index b870857..dd2b9eb 100644 --- a/src/obp/index.ts +++ b/src/obp/index.ts @@ -50,23 +50,50 @@ export async function get(path: string): Promise { } } -export async function create(path: string, body: any): Promise { +export async function create(path: string, body?: any): Promise { try { - return (await superagent.post(`/api/create?path=${path}`) - .set('Content-Type', 'application/json') - .send(JSON.parse(body))) - .body + let request = superagent.post(`/api/create?path=${path}`) + // Only send JSON body if provided and non-empty + if (body !== undefined && body !== null) { + if (typeof body === 'string') { + const trimmed = body.trim() + if (trimmed !== '') { + try { + request = request.set('Content-Type', 'application/json').send(JSON.parse(trimmed)) + } catch (e) { + // If parsing fails, omit body to avoid client-side JSON errors + } + } + } else { + request = request.set('Content-Type', 'application/json').send(body) + } + } + return (await request).body } catch (error) { console.log(error) return { error } } } -export async function update(path: string, body: any): Promise { +export async function update(path: string, body?: any): Promise { try { - return (await superagent.put(`/api/update?path=${path}`) - .set('Content-Type', 'application/json') - .send(JSON.parse(body))).body + let request = superagent.put(`/api/update?path=${path}`) + // Only send JSON body if provided and non-empty + if (body !== undefined && body !== null) { + if (typeof body === 'string') { + const trimmed = body.trim() + if (trimmed !== '') { + try { + request = request.set('Content-Type', 'application/json').send(JSON.parse(trimmed)) + } catch (e) { + // If parsing fails, omit body to avoid client-side JSON errors + } + } + } else { + request = request.set('Content-Type', 'application/json').send(body) + } + } + return (await request).body } catch (error) { console.log(error) return { error }