I am encountering an error related to the router.post("/") function in my JavaScript, express, ejs, and MongoDB project.
The main objective of this post request is to enable users to save a blog post, which will then redirect them to the main page ("/"). As a beginner in this technology stack, any assistance would be greatly appreciated!
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;
**EDIT #1 - The following code snippet is from my server.js file, which I suspect is related 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);