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

Node.js REST API报错:Cannot read property 'password' of undefined 求助

Fixing "Cannot read property 'password' of undefined" in Your Node.js REST API

Hey there, let's break down why you're hitting this error and how to fix it step by step.

The Root Cause

The error Cannot read property 'password' of undefined means that req.body is undefined when you try to access req.body.password. Express doesn't automatically parse incoming request bodies by default—you need to explicitly add middleware to handle that.

Step 1: Add Request Body Parsing Middleware

In your main Express app file (like app.js or server.js), you need to include the built-in Express middleware to parse JSON and form data. Without this, req.body will always be undefined for POST/PUT requests.

Add these lines before mounting your routes:

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

// Parse JSON request bodies
app.use(express.json());
// Parse URL-encoded form data (optional, if you need to handle form submissions)
app.use(express.urlencoded({ extended: true }));

// Now mount your routes
const routes = require('./routes/index');
app.use('/', routes); // Or whatever base path you're using

Step 2: Verify Your Request is Sending Data Correctly

Double-check that your client (Postman, frontend app, etc.) is sending the request properly:

  • Make sure the Content-Type header is set to application/json if you're sending JSON data.
  • Confirm that the password field is actually included in the request body (typos here are super common!).

For example, in Postman:

  1. Go to the Body tab
  2. Select raw and choose JSON from the dropdown
  3. Send a body like:
    {
      "name": "Your Name",
      "password": "yourSecurePassword123"
    }
    

Step 3: Fix a Minor Bcrypt Issue

I noticed you're using bcrypt.hashPassword—this isn't a valid bcrypt method! The correct methods are:

  • Async (recommended): bcrypt.hash()
  • Sync: bcrypt.hashSync()

Here's how to update your route code properly (using async/await for cleaner code):

routes.post('/register', async function(req, res) {
  try {
    // Hash the password asynchronously
    const hashPassword = await bcrypt.hash(req.body.password, 8);
    // Create the user with the hashed password
    const newUser = await User.create({ 
      name: req.body.name, 
      password: hashPassword 
    });
    res.status(201).json(newUser);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

Bonus: Check for Truncated Code

Your snippet cuts off at req.bod...—make sure you're not missing a letter (like req.body instead of req.bod) in your actual code. Small typos can cause big headaches!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:42:43