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

后端发送POST请求时出现错误,请求排查与解决建议

问题分析与修复方案

从错误截图的Cannot read properties of undefined (reading 'post')可直接定位核心问题,结合代码排查出以下几处错误:

1. 路由实例初始化错误

在CreateUser.js中,路由对象创建时缺少函数调用:

// 错误写法
const router = express.Router;
// 正确写法
const router = express.Router();

express.Router是构造函数,必须通过()执行才能生成可用的路由实例,否则router为undefined,调用router.post会抛出"读取post属性失败"的错误。

2. 拼写错误(非功能性但需修正)

接口返回字段seccess属于拼写错误,正确应为success:

// 错误写法
res.json({ seccess: true });
// 正确写法
res.json({ success: true });

3. 数据库连接校验

确保mongoDB()函数正确实现MongoDB连接逻辑,示例实现如下:

// db.js 参考代码
const mongoose = require('mongoose');

const mongoDB = async () => {
  try {
    await mongoose.connect('你的MongoDB连接字符串');
    console.log('数据库连接成功');
  } catch (err) {
    console.error('数据库连接失败:', err);
  }
};

module.exports = mongoDB;

修改后的完整代码

CreateUser.js

const express = require('express');
const router = express.Router(); // 修正路由初始化
const User = require("../models/User");

router.post("/createuser", async (req, res) => {
    try {
        await User.create({
            name: "Badal",
            password: "badal123",
            email: "badal@2.com",
            location: "Jatni"
        })

        res.json({ success: true }); // 修正拼写错误
    } catch (error) {
        console.log(error);
        res.json({ success: false }); // 修正拼写错误
    }
});

module.exports=router;

其他文件说明

  • User.js的Schema定义无问题,字段类型与必填项符合需求;
  • index.js的路由挂载逻辑正确,无需修改。

完成以上修改后重启服务,调用/api/createuser接口即可正常创建用户数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:03:11