You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Express时POST端点无法正常工作——PERN栈日托报告应用问题

Troubleshooting Your PERN Stack POST Endpoint Issue

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-Type header is set to application/json) and check if you get a valid response.
  • Log req.body: Add console.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:10:14