我相信错误是指向router.post(“ /”,....下面的帖子。
我正在使用javascript,express,ejs,mongoDB。
这篇文章的目的是允许您保存一个博客文章(我知道的单词选择不正确),然后将您重定向到主页(“ /”)。我还很新,不胜感激!
const Post = require("../models/post");
const router = express.Router();
// app.set("view engine", "ejs");
router.get("/new", (req, res) => {
res.render("posts/new", { post: new Post() });
});
router.get("/:id", async (req, res) => {
const post = await Post.findById(req.params.id);
if (post == null) res.redirect("/");
res.render("posts/show", { post: post });
});
router.post("/", async (req, res) => {
let post = new Post({
title: req.body.title,
description: req.body.description,
link: req.body.link,
});
try {
post = await post.save();
res.redirect(`/posts/${post.id}`);
} catch (error) {
console.log("failure to create new post");
res.render("posts/new", { post: post });
}
});
module.exports = router;```
**EDIT #1 - The below code is my server.js file that I believe is relevant to the error **
```const express = require("express");
const mongoose = require("mongoose");
const Post = require("./models/post");
const PostModel = require("./models/post");
const postRouter = require("./routes/post");
const app = express();
require("dotenv").config();
app.set("view engine", "ejs");
const connect = () => {
const un = process.env.MONGO_USER;
const pw = process.env.MONGO_PASSWORD;
return mongoose.connect(
`mongodb+srv://${un}:${pw}@personalblog.b6isg.mongodb.net/PersonalBlog?retryWrites=true&w=majority`,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
};
connect().then(async (connection) => {
const createdPost = Post.create();
console.log(createdPost);
console.log(connect());
});
app.get("/", async (req, res) => {
const post = await Post.find().sort({ createdAt: "desc" });
res.render("posts/index", { post: post });
});
app.use("/posts", postRouter);
app.use(express.urlencoded({ extended: false }));
app.listen(4000);```
答案 0 :(得分:0)
req.body在路由器中未定义,这导致了此问题。
在您的app.js中,尝试添加:
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
然后再次发送请求。
答案 1 :(得分:0)
根据您的编码,您使用称为 json 请求的正文
router.post("/", async (req, res) => {
let post = new Post({
title: req.body.title,
description: req.body.description,
link: req.body.link,
});
try {
post = await post.save();
res.redirect(`/posts/${post.id}`);
} catch (error) {
console.log("failure to create new post");
res.render("posts/new", { post: post });
}
});
因此在您的服务器 js 中,改为为 json 注册中间件
// urlencoded parsing
app.use(express.urlencoded({ extended: false }));
// json parsing
app.use(express.json());