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

调用登录API无法获取email,触发TypeError错误求助

解决req.body.email未定义的登录API错误

向http://localhost:4200/api/auth/login发送POST请求时,服务器崩溃并抛出以下错误:

const email = req.body.email;
                         ^
TypeError: Cannot read properties of undefined (reading 'email')
    at loginController 

请求使用的JSON参数为:{ email:'nasta@gmail.com', password:'1423' },且模块文件中能正常打印邮箱和密码,但登录、注册控制器无法正常获取req.body。

解决步骤:

  • 添加JSON请求体解析中间件
    Express框架默认不会自动解析JSON格式的请求体,必须在路由定义前配置express.json()中间件,否则req.body会是undefined。配置示例:

    const express = require('express');
    const app = express();
    
    // 该中间件必须放在所有路由之前
    app.use(express.json());
    
    // 挂载你的认证路由
    app.use('/api/auth', require('./path-to-your-auth-router'));
    
  • 验证请求头配置
    前端发送请求时,必须设置Content-Type: application/json请求头,否则express.json()不会解析请求体。如果使用Fetch API,示例代码如下:

    fetch('http://localhost:4200/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email:'nasta@gmail.com', password:'1423' })
    });
    
  • 检查中间件加载顺序
    确保express.json()中间件在登录、注册路由之前被加载。如果中间件放在路由之后,控制器执行时请求体还未被解析,会导致req.body为undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:45:56