Node.js REST API报错:Cannot read property 'password' of undefined 求助
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-Typeheader is set toapplication/jsonif you're sending JSON data. - Confirm that the
passwordfield is actually included in the request body (typos here are super common!).
For example, in Postman:
- Go to the Body tab
- Select raw and choose JSON from the dropdown
- 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

