简体   繁体   中英

TypeError: Cannot read property 'username' of undefined in node.JS / express cannot post to route

I keep getting a type Error when posting to my exercises. here is my exercises route:

 const router = require("express").Router();
let Exercise = require("../models/exercise.model.js");
//get all exercises
router.get("/", (req, res) => {
  Exercise.find()
    .then(exercises => res.json(exercises))
    .catch(err => res.status(400).json("error: " + err));
});
//add an exercise

router.route("/add").post((res, req) => {
  //parse req.body
  const username = req.body.username;
  const description = req.body.description;
  const duration = Number(req.body.duration);
  const date = Date.parse(req.body.date);
  //create new exercise object
  const newExercise = new Exercise({
    username,
    description,
    duration,
    date
  });
  //save newExercise object
  newExercise
    .save()
    .then(() => res.json("Exercise Added!"))
    .catch(err => res.status(400).json("error: " + err));
});

module.exports = router;

and here is my model:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;
// create exercise data model
const exerciseSchema = new Schema(
  {
    username: {
      type: String,
      required: true
    },
    description: {
      type: String,
      required: true
    },
    duration: {
      type: Number,
      required: true
    },
    date: {
      type: Date,
      required: true
    }
  },
  {
    timestamps: true
  }
);

const Exercise = mongoose.model("Exercise", exerciseSchema);

module.exports = Exercise;

I've tried to change the route to router.post instead of router.route, I've tried changing the data model.

as well as my server.js:

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const cors = require("cors");

//middleware

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
require("dotenv").config();

//environment

const port = process.env.PORT || 5000;

//mongoose establish connection

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true
});

const connection = mongoose.connection;

connection.once("open", () => {
  console.log("MongoDB connection established successfully");
});

//routers for users and exercises

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

app.use("/exercises", exercisesRouter);
app.use("/users", usersRouter);

//error log

app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send(`error: ${err}`).next();
});

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

Here is the error logged in Insomnia: 在此处输入图片说明

Any Help is greatly appreciated!

You are misplace req and res in router.route("/add").post((res, req) => { .

Fix it: router.route("/add").post((req, res) => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM