Blankeos
Blankeos2y ago

await request.json() destructuring body?

// handler
export const registerHTTP = httpAction(async (ctx, request) => {
const { body } = await request.json();

console.log(`Sent via HTTP action: ${body}`);

return new Response(null, {
headers: new Headers({
'Content-Type': 'application/json'
})
});

fetch(url + '/test-api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'test@gmail.com',
username: 'test',
})
}).then(async (res) => {
if (res.ok) {
const json = await res.json();
console.log(json);
}
{
console.log(res.statusText);
}
});
// handler
export const registerHTTP = httpAction(async (ctx, request) => {
const { body } = await request.json();

console.log(`Sent via HTTP action: ${body}`);

return new Response(null, {
headers: new Headers({
'Content-Type': 'application/json'
})
});

fetch(url + '/test-api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'test@gmail.com',
username: 'test',
})
}).then(async (res) => {
if (res.ok) {
const json = await res.json();
console.log(json);
}
{
console.log(res.statusText);
}
});
I'm getting 200, but all I'm getting on the logs is:
log
'Sent via HTTP action: undefined'
log
'Sent via HTTP action: undefined'
4 Replies
lee
lee2y ago
does it work if you do
const body = await request.json();
const body = await request.json();
(without destructuring { body })
Blankeos
BlankeosOP2y ago
Thanks @lee ! That works. Damn I feel stupid haha. I was following this part of the documentation though: https://docs.convex.dev/functions/http-actions#defining-http-actions
// convex/messages.ts
const { author, body } = await request.json();
// convex/messages.ts
const { author, body } = await request.json();
In which case does destructuring work?
HTTP Actions | Convex Developer Hub
HTTP actions allow you to build an HTTP API right in Convex!
lee
lee2y ago
it works in that example because the json being sent has the keys body and author. the json your example sends has keys email and username, so you can destructure const { email, username } = await request.json() we should change the example to avoid using body (maybe call it messageText) to avoid confusion
Blankeos
BlankeosOP2y ago
Got it, thanks for this!

Did you find this page helpful?