Axios 发布错误 TypeError:无法读取未定义的属性“创建”

亡灵矩阵

我正在使用 MERN Stack 构建一个模拟 Facebook 应用程序。当我尝试将帖子保存到我的数据库时,它不断抛出两个错误。一个在后端说TypeError: Cannot read property 'create' of undefined,另一个在前端说Unhandled Rejection (Error): Request failed with status code 500

这是我的前端 API.js 页面

import axios from "axios";

export default {
  // Gets all posts
  getPosts: function() {
    return axios.get("/api/users/posts");
  },
  // Gets the post with the given id
  getPost: function(id) {
    return axios.get("/api/users/posts/" + id);
  },
  // Deletes the post with the given id
  deletePost: function(id) {
    return axios.delete("/api/users/posts/" + id);
  },
  // Saves a post to the database
  savePost: function(postData) {
    return axios.post("/api/users/posts", postData);
  }
};

这是我的 handleSubmit 函数

handleFormSubmit = (event) => {
        // Preventing the default behavior of the form submit (which is to refresh the page)
        event.preventDefault();
        
        // Saving post to database
        API.savePost(this.state)
        .then(data => {
          console.log("data: ", data);
          this.setState({
            title: data.data.title,
            body: data.data.body,
            
          });

        });
      };

这是我的后端 postController.js,TypeError: Cannot read property 'create' of undefined被抛出的地方。

const db = require("../models");
console.log("--------------------------------------");
console.log("Controller Reached");
console.log("--------------------------------------");
// Defining methods for the postController
module.exports = {
  findAll: function(req, res) {
    console.log("----------------------findAll------------------------  ");
    console.log("req.query: ", req.query);
    db.User.posts
      .find(req.query)
      .sort({ date: -1 })
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  },
  findById: function(req, res) {
    db.User.posts
      .findById(req.params.id)
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  },
  create: function(req, res) {
    console.log("create func");
    console.log("req.body: ", req.body);
    db.User.posts
      .create(req.body) //error here
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  },
  update: function(req, res) {
    db.User.posts
      .findOneAndUpdate({ _id: req.params.id }, req.body)
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  },
  remove: function(req, res) {
    db.User.posts
      .findById({ _id: req.params.id })
      .then(dbModel => dbModel.remove())
      .then(dbModel => res.json(dbModel))
      .catch(err => res.status(422).json(err));
  }
};

这些是我的帖子的后端 API 路由(我删除了与问题无关的其他路由)

const router = require("express").Router();
const db = require("../../models");
const passport = require("passport");
const postController = require("../../controllers/postController");

router
  .route("/posts")
  .post(postController.create)
  .get(postController.findAll)
  .put(postController.update)
  .delete(postController.remove);
console.log("/posts reached");

// Matches with "/api/books/:id"
router
  .route("/posts/:id")
  .get(postController.findById)
  .put(postController.update)
  .delete(postController.remove);

//router get for login >>> router.get("/")
//router post for logout
//router.get for profile page

module.exports = router;

编辑:这是我的用户模型

const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const passport = require("passport");
const Schema = mongoose.Schema;
//const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new Schema({
    email: {type: String, required: true},
    password: {type: String, required: true},
    firstname: String,
    lastname: String,
    following: [{
        User: String,
        id: {type: mongoose.Schema.Types.ObjectId }
    }],
    followers: [{
        User: String,
        id: {type: mongoose.Schema.Types.ObjectId }
    }],
    posts: [{
        title: String,
        body: String,
        postedBy: {type: mongoose.Schema.Types.ObjectId},
        dateCreated: Date,
        comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
    }],
    dateCreated: Date,
    savedFiles:[{}],
    favoritePosts: [],
    avatarImage: [{Image: String}],
    jumboImg: [{Image: String}],
    profile: {
        job: String,
        location: String,
        school: String,
        bio: String,
        interests: []
    }
});

var User = (module.exports = mongoose.model("User", userSchema));
module.exports.createUser = function (newUser, callback) {
  console.log("createUser - newUser", newUser)
  bcrypt.genSalt(10, function (err, salt) {
    bcrypt.hash(newUser.password, salt, function (err, hash) {
      newUser.password = hash;
      newUser.save(callback);
    });
  });
};
module.exports.getUserByEmail = function (email, callback) {
  console.log("getUserByEmail", email)
  var query = { email: email };
  console.log(query);
  User.findOne(query, callback);
};
module.exports.getUserById = function (id, callback) {
  console.log("getUserById", id);
  User.findById(id, callback);
};
module.exports.comparePassword = function (candidatePassword, hash, callback) {
  console.log("comparePassword")
  bcrypt.compare(candidatePassword, hash, function (err, isMatch) {
    if (err) throw err;
    callback(null, isMatch);
  });
};
var LocalStrategy = require("passport-local").Strategy;
passport.use(
  new LocalStrategy({ usernameField: "email" }, function (
    email,
    password,
    done
  ) {
    console.log("LocalStrategy");
    User.getUserByEmail(email, function (err, user) {
      if (err) throw err;
      if (!user) {
        return done(null, false, { message: "Unknown User" });
      }
      User.comparePassword(password, user.password, function (err, isMatch) {
        if (err) throw err;
        if (isMatch) {
          return done(null, user);
        } else {
          return done(null, false, { message: "Invalid password" });
        }
      });
    });
  })
);
passport.serializeUser(function (user, done) {
  console.log("serializeUser", user.id)
  done(null, user.id);
});
passport.deserializeUser(function (id, done) {
  console.log("deserializeUser", id);
  User.getUserById(id, function (err, user) {
    console.log("deserializeUser - user", `name="${user.name}" \nemail="${user.email}"\npassword=${user.password} `);
    done(err, user);
  });
});

任何帮助将不胜感激。

射击场

User.postsundefined因为.posts是 的实例的属性User因此,您需要先实例化用户。在这种情况下,通过从 User 集合中查找现有对象。

由于您定义User.posts为原始数组,而不是对另一个集合的引用,因此代码将如下所示。

create: function (req, res) {
  // 1. find the existing user (I guess passport does the job)
  db.User.findById(req.body.userid).then((user) => {
    // 2. add an post
    user.posts.push({
      title: req.body.title,
      body: req.body.body,
      postedBy: req.body.userid,
      dateCreated: Date.now(),
      comments: [],
    });

    // 3. persist the changes
    user.save();
  });
}

如果你想分离集合,我相信这更好,你需要在分离的集合上创建一个新对象,并引用发布的用户。

// Post schema
var postSchema = new Schema({
  title: String,
  body: String,
  postedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
  dateCreated: Date,
  comments: [{ body: "string", by: mongoose.Schema.Types.ObjectId }],
});

// The controller
create: function(req, res) {
  // 1. find the existing user (or you get id from Passport session)
  db.User.findById(req.body.userid).then((user) => {
    // 2. add an post set "postedBy" as the user
    return Post.create({
      postedBy: user._id,
      title: req.body.title,
      body: req.body.body,
      dateCreated: Date.now(),
    });
  });
}

这是关于引用的官方文档:https : //mongoosejs.com/docs/populate.html

希望这可以帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Axios在React中未定义,错误:Uncaught TypeError:无法读取未定义的属性“ post”

TypeError:无法读取未定义的属性'map'(axios => getData => setState => .map => return elmItem =>错误)

用Jest模拟axios会引发错误“无法读取未定义的属性'interceptors'”

Vue.js通过Axios消耗API给出错误:未捕获(已承诺)TypeError:无法读取未定义的属性“协议”

反应 - 错误:TypeError:无法读取未定义的属性(读取“then”)

“TypeError:无法读取未定义的属性(读取'hasOwnProperty')”错误

类型错误:无法在反应 JS 中读取 axios 响应中未定义的属性“setState”获取数据

将 axios 获取的道具从父级传递给子级返回“类型错误:无法读取未定义的属性‘x’”

尝试创建Google图表时遇到错误Uncaught TypeError:无法读取未定义的属性'arrayToDataTable'

Vue - 创建的钩子错误:“TypeError:无法读取未定义的属性‘then’”

AuthenticationController 总是抛出错误,TypeError:无法读取未定义的属性“创建”

作为错误:TypeError:无法读取未定义的属性“位置”

TypeError中的错误:无法读取未定义的属性“标志”

错误TypeError:无法读取未定义的属性'length'

错误TypeError:无法读取未定义的属性“调用”

错误TypeError:无法读取未定义的属性“打开”

错误TypeError:无法读取角度未定义的属性'closeRow'

错误TypeError:无法读取未定义的属性“匹配”

nodejs 收到错误 TypeError:无法读取未定义的属性“then”

错误TypeError:无法读取未定义的属性'grower'

呈现错误:“ TypeError:无法读取未定义的属性'text'”

错误TypeError:无法读取未定义的属性'get'

错误TypeError:无法读取未定义的属性'nativeElement'

角度-错误TypeError:无法读取未定义的属性'title'

FormGroup错误TypeError:无法读取未定义的属性“ get”

错误TypeError:无法读取未定义的属性'firstName'

错误TypeError:无法读取未定义的属性'property'

reactjs错误-TypeError:无法读取未定义的属性“地图”

错误TypeError:无法读取未定义的属性'ngInjectableDef'