Node.js新手求助:PUT接口无法更新数据库数据
Fixing Your Node.js PUT Endpoint for Database Updates
Hey there! Let's break down why your PUT endpoint isn't updating your orders table correctly. I noticed a couple of key issues in your code that are stopping the update from working as expected.
Key Issues in Your Current Code
- Hardcoded Status Value: You're pulling
statusfrom the request body but then hardcoding"Complete"in your SQL query. That means no matter what status the frontend sends, the database will always set it to "Complete"—not exactly dynamic! - Incorrect Parameter Binding: Your SQL query only has one placeholder (
?) fororderID, but you're passing two parameters ([status, orderID]) in the wrong order. This not only wastes thestatusvalue but can also cause unexpected query behavior.
Corrected Code
app.put('/orders/:id', (req, res) => { pool.getConnection((err, connection) => { if (err) { console.error('Error connecting to database:', err); return res.status(500).send('Failed to connect to database'); } console.log(`Connected as id ${connection.threadId}`); // Destructure and validate request body parameters const { orderID, status } = req.body; if (!orderID || !status) { connection.release(); return res.status(400).send('Missing required fields: orderID and status are required'); } // Use placeholders for both status and orderID, with correct parameter order connection.query( 'UPDATE orders SET status = ? WHERE orderID = ?', [status, orderID], (err, rows) => { connection.release(); if (!err) { if (rows.affectedRows === 0) { return res.status(404).send(`Order ${orderID} not found`); } res.send(`Order ${orderID} has been updated to status: ${status}`); } else { console.error('Error updating order:', err); res.status(500).send('Failed to update order'); } } ); }); });
What Changed & Why
- Dynamic Status Value: Replaced the hardcoded
"Complete"with a placeholder (?) so thestatusfrom the request body is actually used in the update. - Correct Parameter Order: The parameters array
[status, orderID]now matches the order of placeholders in the SQL query (SET status = ?first, thenWHERE orderID = ?). - Added Validation: Check if
orderIDandstatusexist in the request body to avoid invalid queries. - Better Error Handling: Return appropriate HTTP status codes (400 for bad requests, 404 for missing orders, 500 for server errors) and user-friendly messages instead of just throwing errors or logging them.
- Check Affected Rows: Verify if any rows were updated to handle cases where the
orderIDdoesn't exist in the database.
内容的提问来源于stack exchange,提问作者Siyabonga Mntungwa
相关产品推荐
相关产品推荐

