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

使用Express将HTML表单数据存入MongoDB时遇404及数据未保存问题

Hey there! Let’s figure out why your form submission is hitting a "Not Found" error and failing to save data to MongoDB. Based on the code snippet you shared, here are the most common issues to check and fix:

1. Route Mismatch (The Top Cause of 404s)

Your code uses router but there’s no sign you’ve mounted it to your Express app, and your form’s submission path might not align with your defined route.

  • Fix steps:
    • Make sure you register your router with the app:
      app.use('/', router); // Adjust the path if your router handles a specific prefix
      
    • Double-check your form’s action attribute. If your form looks like <form action="/submit-form" method="POST">, your router needs a matching POST route:
      router.post('/submit-form', (req, res) => {
        // Handle form data here
      });
      
    • Don’t forget to let Express parse form data! Add this line before your routes:
      app.use(express.urlencoded({ extended: true }));
      
2. Missing Mongoose Model & Schema

You’ve connected to MongoDB, but you haven’t defined a schema/model to structure and save your form data. Without this, there’s no way to persist the data.

  • Fix steps:
    • Create a schema and model for your form data:
      const mongoose = require('mongoose');
      const FormSchema = new mongoose.Schema({
        // Match these fields to your form's input names
        name: String,
        email: String,
        message: String
      });
      const FormEntry = mongoose.model('FormEntry', FormSchema);
      
    • Use this model in your route handler to save data:
      router.post('/submit-form', async (req, res) => {
        try {
          const newEntry = new FormEntry(req.body);
          await newEntry.save();
          res.send('Data saved successfully!');
        } catch (err) {
          res.status(500).send(`Error saving data: ${err.message}`);
        }
      });
      
3. Unhandled Database Connection Issues

Your connection code doesn’t include error handling, so you might not realize if MongoDB isn’t connecting properly.

  • Fix steps:
    • Add connection status listeners to debug:
      const db = mongoose.connection;
      db.on('error', console.error.bind(console, 'MongoDB connection error:'));
      db.once('open', () => {
        console.log('Successfully connected to MongoDB!');
      });
      
    • Make sure your local MongoDB service is running (use the mongod command in your terminal) and that your connection string points to the right database.
4. Mismatched Request Methods

If your form uses method="GET" but your route is defined with router.post(), or vice versa, you’ll get a 404.

  • Fix steps:
    • Ensure your form’s method attribute matches your route’s HTTP method. For form submissions, POST is almost always the right choice.
Full Working Example

Here’s a consolidated version of the code that ties everything together:

const express = require('express');
const app = express();
const mongoose = require('mongoose');

// Parse form data
app.use(express.urlencoded({ extended: true }));

// Connect to MongoDB
const mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => console.log('Connected to MongoDB'));

// Define model
const FormEntrySchema = new mongoose.Schema({
  username: String,
  email: String,
  message: String
});
const FormEntry = mongoose.model('FormEntry', FormEntrySchema);

// Form submission route
app.post('/submit-form', async (req, res) => {
  try {
    const newEntry = new FormEntry(req.body);
    await newEntry.save();
    res.redirect('/success');
  } catch (err) {
    res.status(500).send(`Failed to save data: ${err.message}`);
  }
});

// Serve form page
app.get('/', (req, res) => {
  res.send(`
    <form action="/submit-form" method="POST">
      <input type="text" name="username" placeholder="Username" required>
      <input type="email" name="email" placeholder="Email" required>
      <textarea name="message" placeholder="Your message"></textarea>
      <button type="submit">Submit</button>
    </form>
  `);
});

// Success page
app.get('/success', (req, res) => {
  res.send('Your data has been saved successfully!');
});

// Start server
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

Quick final checks:

  • Make sure your form input name attributes match the fields in your Mongoose schema.
  • Check your terminal for any error messages—they’ll often point you directly to the problem.

内容的提问来源于stack exchange,提问作者s4tr2

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:09:27