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

Angular.js向Node.js(Express)发送JSON出现TypeError问题求助

Fixing "TypeError: Cannot read property 'username' of undefined" in Express + Angular.js

Hey there, let's get this error sorted out quickly! The issue boils down to two key mistakes in your Express backend code:

1. You're accessing the wrong property for POST data

In Express, parsed JSON data from a POST request lives in req.body, not req.data. When you try to access req.data.username, req.data is undefined — that's exactly why you're seeing this error.

2. Express doesn't parse JSON request bodies by default

You need to add a middleware to tell Express to process incoming JSON payloads. Here's how to fix this based on your Express version:

For Express 4.16.0 and newer (most common today)

Express has built-in JSON parsing, so just add this line before your route definitions:

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

// Add this middleware to parse JSON request bodies
app.use(express.json());

// Updated login route
app.post('/api/login', function(req, res) {
  // Use req.body instead of req.data
  console.log(req.body.username);
  console.log(req.body.password);
  // Don't forget to send a response back to Angular!
  res.status(200).json({ message: 'Login data received successfully' });
});

For older Express versions (pre-4.16)

First install the body-parser package via npm:

npm install body-parser

Then use it in your code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// Parse JSON request bodies
app.use(bodyParser.json());

// Updated login route
app.post('/api/login', function(req, res) {
  console.log(req.body.username);
  console.log(req.body.password);
  res.status(200).send('Login data received');
});

Quick check on your Angular code

Your frontend code looks perfect! Angular's $http.post automatically sets the Content-Type: application/json header, which matches what the Express middleware expects — no changes needed there. Just remember to send a response from your Express route (like the examples above) so your Angular then handler doesn't hang waiting for a reply.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:04:17