使用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:
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
actionattribute. 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 }));
- Make sure you register your router with the app:
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}`); } });
- Create a schema and model for your form data:
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
mongodcommand in your terminal) and that your connection string points to the right database.
- Add connection status listeners to debug:
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
methodattribute matches your route’s HTTP method. For form submissions,POSTis almost always the right choice.
- Ensure your form’s
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
nameattributes 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

