Post request returns only list
Hello i am trying to create basic API from nuxt server and i have created 2 files one for the list and one for the post and the shema is correct and the payload from the client matching the schema but the post request always retuns the list not the new obj is there any solution for this ?
3 Replies
Hi @Radwa. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
I'm sorry, but the knowledge sources do not contain enough information to explain why your Nuxt server POST request always returns the list instead of the new object. The sources do provide examples of how to handle POST requests and return the request body or a custom response using Nuxt server API routes:
When you make a POST request from the client:
The handler should return the data you send, not a list, unless your handler is explicitly coded to return a list instead of the new object. Please check your POST handler to ensure it returns the newly created object, not the result of a list-fetching function or variable. If you need further help, please provide the code for your POST handler and the related list handler so I can give more specific advice based on the examples in the documentation Nuxt 3 Server Directory Structure - Body Handling.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
<@1016324722209865761> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
here is my post file code
import { connectDB } from "~/server/utils/mongoose";
import Order from "~/server/models/order";
export default defineEventHandler(async (event) => {
await connectDB();
const body = await readBody(event);
console.log("--- DEBUG: Incoming Order Body ---", body);
try {
const newOrder = await Order.create(body);
setResponseStatus(event, 201);
console.log("--- DEBUG: Created Order Success ---", newOrder._id);
return newOrder;
} catch (error) {
// CRITICAL STEP: THIS WILL CATCH THE HIDDEN ERROR
console.error("--- ERROR: Order Creation Failed ---", error);
// Mongoose Validation Error (e.g., required field missing)
if (error.name === "ValidationError") {
throw createError({
statusCode: 400,
statusMessage:
"Validation Failed: Check required fields or data types.",
data: error.errors, // Send back specific validation details if needed
});
}
// Other errors (DB connection issue, internal error)
throw createError({
statusCode: 500,
statusMessage: "Internal Server Error during order creation.",
});
}
});
check