我正在尝试添加一些基本注释,但显示属性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>
<%});%>
嗨,我认为问题是您需要body-parser
,但尚未设置。
告诉app
使用body-parser
app.use(bodyparser.json()); // support json encoded bodies
app.use(bodyparser.urlencoded({ extended: true })); // support encoded bodies
有关信息see here