EJS / Mongoose - посты, как правило, отображаются дважды после POST. Когда я пытаюсь получить ту же страницу, она появляется дважды? - PullRequest
0 голосов
/ 26 июня 2019

Ну, в основном, когда я POST создаю пост-контроллер, пост появляется один раз, проблема в том, что когда я ПОЛУЧАЮ одну и ту же страницу, он появляется дважды?

Как я могу решить эту проблему, чтобы, если пост уже существовал, тогда он не показывался в другой раз, даже когда я ПОЛУЧИЛ страницу?

Моя цель состоит в том, чтобы пользовательский пост илиполучает страницу, она все равно должна отображаться один раз, если она существует.

контроллер администратора

const path = require('path');
const bcrypt = require("bcryptjs");
const mongoose = require("mongoose");
const _ = require("lodash");
const {
    User,
    Post,
} = require("../models/model");

exports.getMyPostsPage = (req, res) => {
    res.render("admin/myposts", {
        path: "/myposts",
        pageTitle: "My Posts",
    })
}

exports.getCreatepostPage = (req, res) => {
    res.render("admin/createpost", {
        path: "/create",
        pageTitle: "Create",
    });
}


exports.getPostsPage = async (req, res) => {
    try {
        const posts = await Post.find({})

        res.render("admin/posts", {
            path: "/posts",
            pageTitle: "Posts",
            posts: posts
        });
    } catch (err) {
        console.log(err);
    }


}

exports.postCreatePost = async (req, res) => {

    const {
        title,
        description,
        context
    } = req.body;

    const post = new Post({
        title,
        description,
        context,
        author: req.user
    });

    try {
        const savedPost = await post.save()
        const usersPost = await req.user.posts.push(post);
        console.log(req.user.posts)
        const posts = await Post.find({})
        res.render("admin/posts", {
            pageTitle: "Posts",
            path: "/posts",
            posts: posts
        })
    } catch (err) {
        console.log(err);
    }

}

posts.ejs

<%- include("../includes/head.ejs") %>
<link rel="stylesheet" href="/css/admin.css">
</head>

<body>
    <%- include("../includes/navigation.ejs", ) %>
    <% for (const post of posts) { %>
    <div class="posts">
        <form action="/post" method="POST">
            <h1><%=post.title%></h1>
            <p><%=post.description%></p>
            <input type="hidden" name="_csrf" value="<%= csrfToken %>">

            <button type="submit">
                See Post
            </button>


        </form>

    </div>
    <% } %>

    <%- include("../includes/footer.ejs") %>
const mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    bcrypt = require("bcryptjs");




const postSchema = new Schema({
    title: String,
    description: String,
    context: String,
    author: {
        type: Schema.Types.ObjectId,
    }
});


const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },

    email: {
        type: String,
        required: true,
    },

    password: {
        type: String,
        required: true
    },

    posts: [postSchema]
});


userSchema.pre("save", async function save(next) {
    const user = this;
    if (!user.isModified("password")) return next();
    const hashedPassword = await bcrypt.hash(user.password, 10);
    user.password = hashedPassword;
    next();
});


const Post = mongoose.model("Post", postSchema);
const User = mongoose.model("User", userSchema);

module.exports = {
    User,
    Post
}

1 Ответ

0 голосов
/ 26 июня 2019

У меня была проблема, когда дело дошло до использования кнопки f5, она повторила часть POST, но теперь все нормально, на самом деле это была не настоящая проблема, просто ошибка, если можно так выразиться.

...