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

Node.js中cannot POST /报错求助:无法向数据库添加数据

Fixing the "cannot POST /" Error & Database Insert Issues in Your Node.js App

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

  1. Apply all the fixes above
  2. Restart your Node.js server
  3. Log in to your app, navigate to /new
  4. Fill out the form and upload a valid image (jpg/png/gif)
  5. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:28:35