bugfix/Refactor API request handling in Preview component and obp module to ensure safe body parsing and conditional sending. Updated create and update functions to handle optional body parameters and prevent errors from empty or invalid JSON inputs.

This commit is contained in:
Hongwei 2025-10-06 15:39:51 +02:00
parent de1feb9fa2
commit 2ae8f18462
2 changed files with 56 additions and 11 deletions

View File

@ -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': {

View File

@ -50,23 +50,50 @@ export async function get(path: string): Promise<any> {
}
}
export async function create(path: string, body: any): Promise<any> {
export async function create(path: string, body?: any): Promise<any> {
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<any> {
export async function update(path: string, body?: any): Promise<any> {
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 }