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

Node.js注册时出现TypeError: Cannot read property 'length' of undefined求助

Fixing Your Node.js Registration Issues

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 name attributes. If your password input has name="password", your confirm password input needs a matching name that your backend is looking for (like name="confirmPassword"). If your backend is trying to access req.body.password2 but your frontend uses confirmPassword, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:21:49