简体   繁体   English

使用节点 JS 向 MongoDB 添加数据,我收到此错误:“TypeError: Cannot read property 'username' of undefined”

[英]Adding data to MongoDB using node JS and I get this error: “TypeError: Cannot read property 'username' of undefined”

I am trying to add to mongo DB some data using a POST request sent from postman application.我正在尝试使用从 postman 应用程序发送的 POST 请求向 mongo DB 添加一些数据。 I have successfully created the database and a message was printed indicating that.我已经成功创建了数据库,并打印了一条消息表明这一点。 Below is my code:下面是我的代码:

users.js file: 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:用户.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: 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");
});

Now, using Postman, I send a POST request to the link: "http://localhost:5000/users/add" and I get a message saying:现在,使用 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)

I searched for the questions and tried all the suggested answers (which are too few) and none worked for me.我搜索了问题并尝试了所有建议的答案(太少了),但没有一个对我有用。

Basically, in NodeJs and Express Middleware functions have access to req , res object and next function in the req-res cycle Middleware .基本上,在NodeJsExpress Middleware中,函数可以访问reqres object 和next function 在req-res循环Middleware The task of the middleware functions are中间件功能的任务是

  • Execute any code执行任何代码
  • End req res cycle and also make changes to req res cycle结束req res周期并更改req res周期

You need to have body-parser middleware.你需要有body-parser中间件。 It parses the incoming request bodies in a middleware before your handlers.它在处理程序之前解析中间件中的传入请求主体。

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

More on bodyParser middleware bodyParser .更多关于bodyParser middleware bodyParser

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 类型错误:无法读取未定义的属性“get”:节点 js 错误 - TypeError: Cannot read property 'get' of undefined: A node js error TypeError:无法读取Node JS中未定义的属性“用户名” - TypeError: Cannot read property 'username' of undefined in Node JS Node.js和mongodb:TypeError:无法读取未定义的属性'findAll' - Node.js and mongodb: TypeError: Cannot read property 'findAll' of undefined 使用本机 mongoDB 驱动程序、Node.js 和超级终端时,我收到一条错误消息“TypeError:无法读取未定义的属性‘n’” - When working with the native mongoDB driver, Node.js and hyper terminal, I receive an error saying "TypeError: Cannot read property 'n' of undefined" TypeError:无法读取未定义的属性“ get”(Node.js) - TypeError: Cannot read property 'get' of undefined (Node.js) (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“用户名” - (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined 类型错误:无法读取未定义的 Discord.js 错误的属性“get” - TypeError: Cannot read property 'get' of undefined Discord.js Error 当我尝试使用tensorflow.js模型进行预测时,出现错误:Uncaught TypeError:无法读取未定义的属性“ length” - When I try to make a prediction using a tensorflow.js model I get the error: Uncaught TypeError: Cannot read property 'length' of undefined TypeError:无法读取未定义 React JS 的属性“用户名” - TypeError: Cannot read property 'username' of undefined React JS 类型错误:无法读取未定义的 discord.js 的属性“用户名” - TypeError: Cannot read property 'username' of undefined discord.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM