N
Nuxt2y ago
tierra

server api useBody not working ?

Hi for me, the most simple example is not working: https://nuxt.com/docs/guide/directory-structure/server#handling-requests-with-body Somehow the body is not received / read. Also I found out that $fetch from the example should be changed to useFetch... So my setup is this: some component
async function onSubmit() {
const { data } = await useFetch("/api/newsletter/signup", {
method: "post",
body: { email: email?.value },
});
console.log(data?.value); // returns `{}`
}
async function onSubmit() {
const { data } = await useFetch("/api/newsletter/signup", {
method: "post",
body: { email: email?.value },
});
console.log(data?.value); // returns `{}`
}
my /api/newsletter/signup.post.js
export default defineEventHandler(async (event) => {
const payload = await readBody(event);
return { payload }; // returns {}
});
export default defineEventHandler(async (event) => {
const payload = await readBody(event);
return { payload }; // returns {}
});
anyone has any idea what I am doing wrong?
Nuxt
server/
The server/ directory is used to register API and server handlers to your application.
4 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Fabian B.
Fabian B.2y ago
Hi, it's readBody, not useBody. Did you get it to work?
tierra
tierraOP2y ago
Thanks, I wasn't usign useBody as you can see in my example, I already figured this out. But still, nothing will be returned. I am also experienceing debugging problems, for instance I change the code in my server/api folder but I would not update, even after restarting the server. I am on nuxt 3.2.0 but had the same with 3.1.2 So I logged some things newsletter.post.ts
export default defineEventHandler(async (event) => {
console.log(event);
const payload = await readBody(event);
console.log(payload);
return {
test: "abc",
email: payload,
};
});
export default defineEventHandler(async (event) => {
console.log(event);
const payload = await readBody(event);
console.log(payload);
return {
test: "abc",
email: payload,
};
});
Update: Ifound out this was because of my routeRules in my nuxt.config.ts
Fabian B.
Fabian B.2y ago
Interesting, so is this thread solved?
Want results from more Discord servers?
Add your server