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

Express中req.body未定义引发TypeError,请求协助实现数据库数据存储

解决Express中req.body undefined导致无法存入数据库的问题

错误原因

你遇到的TypeError: Cannot read properties of undefined (reading 'description'),核心原因是Express默认不会自动解析HTTP请求体,所以req.body是undefined,无法读取其中的description属性。

解决步骤

1. 添加请求体解析中间件

在你的主Express应用文件(通常是app.js或server.js)中,必须在挂载路由之前添加解析请求体的中间件,这是关键步骤:

  • 处理表单提交的application/x-www-form-urlencoded格式数据:
    app.use(express.urlencoded({ extended: true }));
    
  • 如果需要同时支持JSON格式的请求,再追加:
    app.use(express.json());
    

示例主文件结构:

const express = require('express');
const app = express();
// 引入你的路由文件
const taskRouter = require('./routes/你的路由文件名');

// 配置请求体解析中间件(必须在挂载路由之前)
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// 挂载路由
app.use('/', taskRouter);

// 启动服务器
app.listen(3000, () => {
    console.log('服务器运行在 http://localhost:3000');
});

2. 优化路由代码的错误处理与响应

你的路由代码有两处需要调整:

  • catch块直接throw error会导致服务器崩溃,应该返回错误响应给客户端
  • res.render('/')用法错误,若要回到首页,用res.redirect('/')重定向,或使用正确的视图文件名调用render

修改后的路由代码:

const express = require('express');
const router = express.Router();
const homeController = require('../Controller/homeController');
const addTask = require('../models/schema');

router.get('/', homeController.home);
router.get('/task', homeController.task);

router.post('/addTask', async (req, res) => {
    try {
        // 可选:校验请求数据是否存在
        if (!req.body?.description) {
            return res.status(400).send('任务描述不能为空');
        }

        const todoTask = new addTask({
            description: req.body.description,
            category: req.body.category,
            date: req.body.date
        });

        await todoTask.save();
        // 重定向到首页
        res.redirect('/');
    } catch (error) {
        console.error('保存任务失败:', error);
        res.status(500).send('保存任务失败,请稍后重试');
    }
});

module.exports = router;

额外注意事项

  • 确保前端表单的name属性和你在req.body中读取的字段名一致(比如表单输入框的name="description")
  • extended: true允许解析复杂的对象和数组,若不需要可以设为false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:32:22