gpt4 book ai didi

javascript - 未处理的 promise 拒绝警告 : TypeError: Cannot read property 'title' of undefined

转载 作者:行者123 更新时间:2023-12-03 06:55:40 26 4
gpt4 key购买 nike

我相信错误指向 router.post("/", .... 下面的帖子。
我正在使用 JavaScript、express、ejs、mongoDB。
这篇文章的目的是让您保存一篇博客文章(我知道的单词选择令人困惑),然后将您重定向到主页(“/”)。我是相当新的,任何帮助表示赞赏!

const express = require("express");
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;

**编辑 #1 - 下面的代码是我的 server.js 文件,我认为它与错误相关**
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);

最佳答案

req.body 在导致此问题的路由器中未定义。
在您的 app.js 中,尝试添加:

app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
并再次发送请求。

关于javascript - 未处理的 promise 拒绝警告 : TypeError: Cannot read property 'title' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63986109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com