【问题标题】:Adding data to MongoDB using node JS and I get this error: "TypeError: Cannot read property 'username' of undefined"使用节点 JS 向 MongoDB 添加数据,我收到此错误:“TypeError: Cannot read property 'username' of undefined”
【发布时间】:2020-07-03 18:39:41
【问题描述】:

我正在尝试使用从邮递员应用程序发送的 POST 请求向 mongo DB 添加一些数据。我已经成功创建了数据库,并打印了一条消息表明这一点。以下是我的代码:

users.js 文件:

const router = require("express").Router();
let User = require("../models/user.model"); //the model we created

router.route("/").get((req, res) => {
  //If the link(route) is routes/users/ and it is a get request this is what is going to happen

  //
  User.find() //find: gets all what is in the database
    .then((users) => res.json(users)) //this puts in users all the users values
    .catch((err) => res.status(400).json("Error: " + err));
});

router.route("/add").post((req, res) => {
  //this handles the post requests at routes/users/add
  res.setHeader("Content-Type", "application/json");
  const username = req.body.username; //Gets the username passed

  const newUser = new User({ username }); //creates a new User (User model imported from the other file)

  newUser
    .save() //save: saves the created user in the database
    .then(() => res.json("user added!")) //
    .catch((err) => res.status(400).json("Error: " + err));
});

module.exports = router;

user.model.js:

const { Schema } = require("mongoose");

const mongoose = require("mongoose");
const schema = mongoose.Schema;

const userSchema = new schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3,
    },
  },
  {
    timestamps: true,
  }
);
const User = mongoose.model("User", userSchema); //"User" is the name we are going to use
//userSchema is the name of the schema

module.exports = User;

server.js:

const cors = require("cors");

const mongoose = require("mongoose");

const uri =
  "mongodb+srv://user:71G9XZybFtmljhkO@cluster0.tjfdk.mongodb.net/user?retryWrites=true&w=majority";

mongoose.connect(uri, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});

const connection = mongoose.connection;
connection.once("open", () => {
  console.log("DB Established!");
});

require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
// app.use(cors);

const exerciesesRouter = require("./routes/exercises");
const usersRouter = require("./routes/users");

app.use("/exercises", exerciesesRouter); //if any one goes to /exercise it will load everything inside exerciseRouter
app.use("/users", usersRouter);

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

app.get("/", (req, res) => {
  res.send("hello");
  res.end("ehee");
});

现在,使用 Postman,我向链接发送 POST 请求:“http://localhost:5000/users/add”,然后我收到一条消息:

TypeError: Cannot read property 'username' of undefined
    at router.route.post (F:\code\MERN2\backend\routes\users.js:16:29)
    at Layer.handle [as handle_request] (F:\code\MERN2\backend\node_modules\express\lib\router\layer.js:95:5)
    at next (F:\code\MERN2\backend\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (F:\code\MERN2\backend\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (F:\code\MERN2\backend\node_modules\express\lib\router\layer.js:95:5)
    at F:\code\MERN2\backend\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:335:12)
    at next (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:174:3)
    at router (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (F:\code\MERN2\backend\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:317:13)
    at F:\code\MERN2\backend\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:335:12)
    at next (F:\code\MERN2\backend\node_modules\express\lib\router\index.js:275:10)
    at expressInit (F:\code\MERN2\backend\node_modules\express\lib\middleware\init.js:40:5)

我搜索了问题并尝试了所有建议的答案(太少了),但没有一个对我有用。

【问题讨论】:

  • 你检查req.body.username 打印用户名了吗?

标签: javascript node.js mongodb express postman


【解决方案1】:

基本上,在NodeJsExpress 中,Middleware 函数可以在req-res 循环Middleware 中访问reqres 对象和next 函数。中间件函数的任务是

  • 执行任何代码
  • 结束reqres循环并同时更改reqres循环

你需要有body-parser 中间件。它在处理程序之前解析中间件中的传入请求正文。

//Middlewares for bodyParser
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

更多关于bodyParsermiddlewarebodyParser

【讨论】:

  • 成功了!谢谢!但是,你能再解释一下吗?我没有得到中间件的东西,我仍然是使用 node js 和 mongo db 的初学者。
  • 更新了看看,也请通过附加的链接。
猜你喜欢
  • 2020-09-20
  • 2019-04-05
  • 2023-02-22
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多