Node.js中cannot POST /报错求助:无法向数据库添加数据
Hey there, let’s break down why you’re hitting that cannot POST / error and get your data saving to the database properly. I’ve gone through your code and spotted a few key issues to address:
1. Mismatched Form Submission Route (Root Cause of the POST Error)
Looking at your new.ejs form, the action is set to /:
<form action="/" method="POST" class="was-validated" enctype="multipart/form-data">
But in your index.js, you only have a POST route for /new:
app.post('/new', loginRequired, routes.new);
There’s no handler for POST /, so the server throws the "cannot POST /" error.
Fix: Update your form’s action to point to /new:
<form action="/new" method="POST" class="was-validated" enctype="multipart/form-data">
2. Incorrect File MIME Type Check
In routes.js, you’re checking for file types with images/jpeg (plural), but valid MIME types use the singular image/:
// Wrong if(file.mimetype == "images/jpeg" ||file.mimetype == "images/png"||file.mimetype == "images/gif" ){
This means your file upload check will always fail, and you’ll get the "format not allowed" message.
Fix: Correct the MIME type strings:
// Correct if(file.mimetype == "image/jpeg" || file.mimetype == "image/png" || file.mimetype == "image/gif"){
3. Critical SQL Injection Vulnerability
Right now, you’re directly concatenating user input into your SQL query:
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES ('" + username + "','" + title + "','" + state + "','" + category + "','" + img_name + "','" + description + "')";
This is extremely dangerous—malicious users can inject SQL code to delete or steal your data.
Fix: Use parameterized queries (prepared statements) to safely pass user input:
const sql = "INSERT INTO `nt_data`(`username`,`title`,`state`,`category`, `images` ,`description`) VALUES (?, ?, ?, ?, ?, ?)"; const query = con.query(sql, [username, title, state, category, img_name, description], function(err, result) { if(err) { console.error(err); return res.status(500).send("Failed to save data"); } // Redirect to the show page for the correct username res.redirect('/show/' + username); });
4. Broken Redirect After Insert
Your current redirect uses result.insertUsername, which doesn’t exist in the MySQL query result. The INSERT result returns an insertId (for auto-increment primary keys), but since you’re using username to fetch data, you should redirect using the username variable directly. Also, always use an absolute path (/show/...) to avoid relative path issues.
Fix: Update the redirect line as shown in the parameterized query example above.
5. Unnecessary Global Session Variable
In index.js, you’re assigning s = req.session; in the loginRequired middleware. This global variable can cause bugs in concurrent requests (multiple users logged in at the same time). You don’t need it—just use req.session directly whenever you need session data.
Fix: Remove the let s; declaration and the s = req.session; line.
Final Steps to Test
- Apply all the fixes above
- Restart your Node.js server
- Log in to your app, navigate to
/new - Fill out the form and upload a valid image (jpg/png/gif)
- You should be redirected to the
/show/[username]page and see your new data in the database
Let me know if you hit any snags after making these changes!
内容的提问来源于stack exchange,提问作者user14398337

