Node.js注册时出现TypeError: Cannot read property 'length' of undefined求助
Hey there! Let's work through these problems you're facing with your registration feature—since you're new to Node.js, I'll keep this clear and actionable.
First: Fix the "Cannot read property 'length' of undefined" Error
This error means your server isn't properly reading the form data sent from the browser, so req.body.password is coming up as undefined. Here's how to fix it:
You need to add Express's built-in middleware to parse incoming request bodies. Put these lines before your route definitions in your main server file (like app.js or server.js):
// For parsing traditional form data (application/x-www-form-urlencoded) app.use(express.urlencoded({ extended: true })); // If you're sending JSON data (optional, but useful for API-style requests) app.use(express.json());
Without this middleware, Express can't access the data from your registration form in req.body, which is why password is undefined.
Second: Fix the "Passwords Don't Match" Issue
Even after commenting out the length check, you're still getting a password mismatch? Let's look at the most common causes:
- Mismatched field names: Double-check your frontend form's
nameattributes. If your password input hasname="password", your confirm password input needs a matching name that your backend is looking for (likename="confirmPassword"). If your backend is trying to accessreq.body.password2but your frontend usesconfirmPassword, they'll never match! - Typos in your comparison logic: Make sure your password check is written correctly. For example, if you accidentally flipped the condition, it would trigger the error even when passwords are the same. A correct check should look like:
if (req.body.password !== req.body.confirmPassword) { return res.status(400).send("Passwords don't match"); }
Quick Debug Tip
Add a console.log(req.body) at the start of your registration route handler. This will print out all the data your server is receiving from the form. You'll immediately see if password or your confirm password field is missing or has the wrong name.
内容的提问来源于stack exchange,提问作者Ngoy Banza

