Node.js中body-parser返回undefined问题求助
Hey there! Let's figure out why you're not getting that form data in your Express app. The issue here is likely tied to the enctype="multipart/form-data" attribute on your form—here's what's going on and how to fix it:
What's the Problem?
When you set enctype="multipart/form-data", it's designed for forms that need to upload files (like images or documents). Express's built-in express.urlencoded() middleware only handles the default application/x-www-form-urlencoded content type—it can't parse multipart data. That's why your req.body is coming up empty when you try to access the input value.
Solution 1: Simplify Your Form (For Text-Only Input)
If you're only collecting text input (no file uploads), you don't need multipart/form-data at all. Here's how to fix this:
- Update your EJS form to remove the
enctypeattribute (the defaultapplication/x-www-form-urlencodedworks perfectly for text):
<form action="/input" method="POST"> <div class="input-group"> <input type="text" class="form-control" name="userInput" placeholder="Enter your search..."> <button type="submit" class="btn btn-primary">Submit</button> </div> </form>
(Make sure your input's name attribute is complete—your snippet had name="i..., so fill that in with something like userInput.)
- Ensure your Express app uses the built-in urlencoded middleware (this is included with Express 4.16+):
const express = require('express'); const app = express(); // Configure middleware to parse text form data app.use(express.urlencoded({ extended: true })); // Set EJS as your template engine app.set('view engine', 'ejs'); // Handle the POST request to /input app.post('/input', (req, res) => { // Now you can access the input value via req.body const inputData = req.body.userInput; console.log('Received input:', inputData); res.send(`You entered: ${inputData}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Solution 2: Use Multer For Multipart Data (If You Need File Uploads)
If you plan to add file uploads later and want to keep multipart/form-data, you'll need the multer package to parse the form data:
- Install multer:
npm install multer
- Configure multer in your Express app (use
multer().none()to parse only text fields, no files):
const express = require('express'); const multer = require('multer'); const app = express(); // Configure multer to parse text-only multipart data const upload = multer().none(); app.set('view engine', 'ejs'); // Use the upload middleware before handling the request app.post('/input', upload, (req, res) => { const inputData = req.body.userInput; console.log('Received input:', inputData); res.send(`You entered: ${inputData}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Test either solution, and you should see the input data show up in your server console and the response!
内容的提问来源于stack exchange,提问作者J.G.Sable

