使用Express时POST端点无法正常工作——PERN栈日托报告应用问题
Hey there! Let's walk through why your POST endpoint might be misbehaving, since your GET routes are working fine. First, let's start with the obvious gaps in your current code and then cover common PERN-specific pitfalls.
Common Issues & Fixes
1. You're Missing Request Body Parsing Middleware
Express doesn't automatically parse JSON request bodies by default. If you haven't added this middleware, req.body will be undefined—which means your createClassroom function is getting empty data.
Add this line before all your routes in your Express app setup:
app.use(express.json());
2. Incomplete Promise Chain & Missing Error Handling
Your POST code cuts off mid-then block, which means even if createClassroom succeeds, you're never sending a response back to the client. Plus, there's no error handling for database failures.
Here's a complete, fixed version of your POST endpoint:
app.post('/classroomList', (req, res) => { // First, validate required fields (adjust based on your database schema) if (!req.body.class_name) { return res.status(400).json({ error: "Class name is a required field" }); } classroom.createClassroom(req.body) .then((newClassroom) => { // Send back the created classroom with a 201 (Created) status code res.status(201).json(newClassroom); }) .catch((err) => { // Log the error for debugging, then send a user-friendly response console.error("Failed to create classroom:", err); res.status(500).json({ error: "Could not create classroom. Please try again." }); }); });
3. Verify Your createClassroom Database Function
Make sure your classroom.createClassroom method properly returns a Promise and handles errors correctly. For example, if you're using the pg PostgreSQL client for Node.js, it should look something like this:
// Example createClassroom implementation in your classroom model const pool = require('./db'); // Your PostgreSQL pool connection async function createClassroom(classroomData) { const { class_name, teacher_name } = classroomData; try { // Use RETURNING * to get the newly created row from the database const result = await pool.query( "INSERT INTO classrooms (class_name, teacher_name) VALUES ($1, $2) RETURNING *", [class_name, teacher_name] ); return result.rows[0]; // Return the created classroom object } catch (err) { throw err; // Throw the error so the route's .catch() can handle it } } module.exports = { createClassroom, getClassrooms, getStudentsByClass };
Debugging Steps to Confirm
- Test with Postman/Curl: Send a POST request with a JSON body (make sure the
Content-Typeheader is set toapplication/json) and check if you get a valid response. - Log
req.body: Addconsole.log("Request body:", req.body)at the start of your POST route to confirm the data is being parsed correctly. - Check database logs: If the error is on the PostgreSQL side, look at your database logs to see if there are query syntax errors or constraint violations (like missing required fields).
内容的提问来源于stack exchange,提问作者Jaime Ivy Arrestinya Pendlebur

