【问题标题】:NodeJS TypeError: Post is not a ConstructorNodeJS TypeError:帖子不是构造函数
【发布时间】:2020-06-12 17:07:14
【问题描述】:

我有一个公式,我想在提交后收到回复消息。 使用 Node v13.3.0, “快递”:“^4.17.1”, "express-handlebars": "^3.1.0", “快速会话”:“^1.17.0”, "flash": "^1.1.0", "车把": "^4.7.3", “猫鼬”:“^5.9.2”

Post.js

const
    mongoose = require('mongoose');

const Schema = mongoose.Schema; // get props

const PostSchema = new Schema({
    // define props --> required for a post

    surname: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    biography: {
        type: String,
        required: true,
    },
    profilpicture: {
        type: Object,
        required: true,
    }


});

module.exports = mongoose.model('Post', PostSchema);

Controller.js

const Post = require('../models/postModel').Post;
module.exports = {
submitPosts: (req, res) => {
        // res.render('admin/posts/submit');
        // Check the attributs from create.handlebars for success or error message
        const newPost = new Post( {
            surname: req.body.surname,
            name: req.body.name,
            biography: req.body.biography,
            profilpicture: req.body.profilpicture
        });
        // Safe new posts
        newPost.save().then(post => {
            console.log(post);
            flash('success-message', 'Yay its fine')
            res.redirect('/admin');
        });
    },
}

我用于每个输入的公式文件 name="attribut" 如果我删除 Post (Controller.js),它会引发另一个错误:

(node:2296) UnhandledPromiseRejectionWarning: ValidationError: Post validation failed: surname: Path surname is required., name: Path name is required., biography: Path biography is required., profilepicture : 路径 profilpicture 是必需的。 并且网站不会停止加载

【问题讨论】:

  • require('../models/postModel').Post 替换为 require('../models/postModel'),如果这是它唯一导出的内容
  • 已经尝试过了,但它会抛出一个新的错误消息:UnhandledPromiseRejectionWarning: ValidationError: Post validation failed: surname: Path surname is required., name: Path name.. 等等跨度>
  • 好吧,我的错,第一次阅读你的问题时没有弄清楚。但是,这个错误比另一个要好。所以,请删除 .Post。既然这已经不碍事了,那么在尝试创建newPost 之前,您在console.log(req.body.surname) 等时看到正确的数据了吗?
  • 如果我 console.log(req.body.surname) 在它说未定义之前和之后它抛出“未处理的承诺拒绝。这个错误源于在没有 catch 块的异步函数内部抛出,或者通过拒绝未使用 .catch() 处理的承诺。(rejection id: 2)"

标签: javascript node.js mongodb express typeerror


【解决方案1】:

如果它在您执行此操作时记录 undefined

console.log(req.body.surname);

这意味着您没有按预期收到 POST 数据。

确保您使用的是express.urlencoded() 中间件:

const express = require("express");
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true })); // <--------

/* ... */

【讨论】:

  • 我在我的 app.js 中使用它 app.use(express.json()); app.use(express.urlencoded({extended: true }))
  • 好的,你如何从前端发出 POST 请求?您可以将其添加到您的问题中吗?如果表单以x-www-form-urlencoded 发送,则上述内容应该有效
  • 对于form-data,也许是this can help
猜你喜欢
  • 2018-05-24
  • 2019-03-24
  • 2019-08-14
  • 1970-01-01
  • 2018-06-27
  • 2016-04-16
  • 2021-11-26
相关资源
最近更新 更多