TypeError:无法读取未定义的属性'c'

问题描述 投票:0回答:1

我正在尝试添加一些基本注释,但显示属性undefined

TypeError: Cannot read property 'c' of undefined
    at d:\New folder\app.js:19:21
at Layer.handle [as handle_request] (d:\New folder\node_modules\express\lib\router\layer.js:95:5)

app.js

var express = require("express");
var app = express();
var bodyparser = require("body-parser");
app.set("view engine", "ejs");
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/exam", { useNewUrlParser: true, useUnifiedTopology: true });
var examSchema = new mongoose.Schema({
    t: String
});
var Exam = mongoose.model("Exam", examSchema);
// Exam.create({
//     t: "hello"
// });
app.get("/", function(req, res) {
    res.redirect("/c/n");
});
app.post("/c", function(req, res) {
    Exam.create({
        t: req.body.c
    });
    res.redirect("/");
});
app.get("/c/n", function(req, res) {
    Exam.find({}, function(err, all) {
        if (err) {
            console.log(err);
        } else {
            res.render("show", { exams: all });
        }
    })
});

app.listen("3000", function() {
    console.log("server started");
});

show.ejs

<form action="/c" method="post">
    <input class="form-control" type="text" name="c" placeholder="comment">
    <button type="submit">submit</button>
</form>
<% exams.forEach(function(t){%>
    <p>-
        <%=t.t%>
    </p>
    <%});%>
javascript node.js express mongoose ejs
1个回答
0
投票

问题

嗨,我认为问题是您需要body-parser,但尚未设置。

解决方案

告诉app使用body-parser

app.use(bodyparser.json()); // support json encoded bodies
app.use(bodyparser.urlencoded({ extended: true })); // support encoded bodies

有关信息see here

© www.soinside.com 2019 - 2024. All rights reserved.