最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

无法在Express和Mongoose中更新博客应用

运维笔记admin11浏览0评论

无法在Express和Mongoose中更新博客应用

无法在Express和Mongoose中更新博客应用

我正在使用CRUD操作构建一个博客站点。我可以创建,阅读和删除,但我很难弄清楚如何更新创建的帖子。基本上我有它可以点击home.ejs中单个条目的“编辑”按钮,然后进入edit.ejs路径,其中输入字段用当前标题和内容填充。我希望能够编辑内容和标题,然后单击edit.ejs路线上的“发布”以更新内容。但是当我这样做时,它给了我一个错误:无法POST /编辑,也没有更新。我想要它做的是更新单个条目,然后重定向回根路由并反映编辑。在“app.post(”/ edit /:id“)”路线上,我应该使用“PUT”请求来更新帖子吗?如果这很难遵循,我很抱歉。我不太擅长解释事情。我已经绞尽脑汁待了一会儿。任何帮助表示赞赏。

这是相关的代码:

app.js

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");

const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";

let app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/blogDB", {
  useNewUrlParser: true
});

const postSchema = {
  date: String,
  title: String,
  content: String
}

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

app.get("/", (req, res) => {

  Post.find({}, (err, posts) => {
    res.render("home", {
      posts: posts
    });
  });
});

app.get("/about", (req, res) => {
  res.render("about", {
    aboutContent: aboutContent
  });
});

app.get("/contact", (req, res) => {
  res.render("contact", {
    contactContent: contactContent
  });
});

app.get("/compose", (req, res) => {
  res.render("compose");
});


app.post("/compose", (req, res) => {
  const postTitle = req.body.postTitle;
  const postBody = req.body.postBody;

  let date = new Date();
  let postDate = date.toLocaleString('en-US');

  const post = new Post({
    date: postDate,
    title: postTitle,
    content: postBody
  });

  post.save(err => {
    if (!err) {
      res.redirect("/");
    }
  });
});

app.get("/edit/:id", (req, res) => {
  const requestedId = req.params.id;
  console.log(req.body);
  Post.findOne({
    _id: requestedId
  }, (err, post) => {
    if (!err) {
      res.render("edit", {
        title: post.title,
        content: post.content
      });
    }
  });
});

app.post("/edit/:id", (req, res) => {
  const requestedId = req.params.id;
  console.log(req.body);
  Post.findOne({
    _id: requestedId
  }, (err, post) => {
    if (!err) {
      res.render("edit", {
        title: post.title,
        content: post.content
      });
    }
  });
});



app.get("/posts/:id", (req, res) => {
  const requestedId = req.params.id;

  Post.findOne({
    _id: requestedId
  }, (err, post) => {
    if (!err) {
      res.render("post", {
        title: post.title,
        content: post.content
      });
    }
  });
});

app.post("/delete", (req, res) => {
  const deletePost = req.body.delete;

  Post.findByIdAndDelete(deletePost, (err) => {
    if (!err) {
      res.redirect("/");
    }
  });
});

app.listen(3000, function () {
  console.log("Server started on port 3000");
});

home.ejs

<%- include("partials/header") -%>
<h1>Home</h1>
<a href="/compose" class="post-link"><button type="button" class="new-entry btn btn-dark">New Entry</button></a>

<div class="entries-container">
  <% posts.forEach(post => { %>

  <div class="blog-entry">
    <p class="post-date">Posted on
      <%= post.date %>
    </p>
    <h2>
      <%= post.title %>
    </h2>
    <div class="entry-footer">
      <a href="/posts/<%= post._id %>" class="post-link"><button type="button" class="btn btn-outline-primary">VIEW</button></a>
      <form action="/edit" method="POST">
        <a href="/edit/<%= post._id %>" class="post-link" ><button type="button" name="edit" value="<%= post.title %>" class="btn btn-outline-secondary">EDIT</button></a>
      </form>
      <form action="/delete" method="POST">
        <button type="submit" name="delete" value="<%= post._id %>" class="btn btn-outline-danger">DELETE</button>
      </form>
    </div>
  </div>
  <% }) %>
</div>

<%- include("partials/footer") -%>

edit.ejs

<%- include("partials/header") -%>
<h1>Compose</h1>
<form action="/edit" method="PUT">
  <div class="form-group">
    <label for="postTitle">Title</label>
    <input type="text" name="postTitle" class="form-control" id="postTitle" autocomplete="off" value="<%= title %>">
    <label for="postBody">Post</label>
    <textarea name="postBody" class="form-control" autocomplete="off" rows="8"><%= content %></textarea>
  </div>
  <button type="submit" name="button" class="btn btn-primary">Publish</button>
</form>
<%- include("partials/footer") -%>

post.ejs

<%- include("partials/header") -%>
  <h2 class="post-title"><%= title %></h2>
  <p class="post-content"><%= content %></p>
<%- include("partials/footer") -%>
回答如下:

通常你会使用PUT如果你正在进行更新和POST如果你正在创建一个新项目,但说实话,这些单词不强制行为,而是你写的代码。

从您的代码中,您在/ edit /:id上声明了一个get和一个帖子,这不一定是错误的,但它们都有相同的代码。

如果我正在制作博客文章编辑器,我会按如下方式定义我的路线:

GET - /blog - 获取所有博客

GET - /blog/:id - 获得一个博客

POST - /blog - 创建一个新博客

PUT - /blog/:id - 更新现有博客

DELETE - /blog/:id - 删除现有博客

对于您的表单,您将操作设置为PUT,但您没有在快速应用程序中声明的相应PUT路由。

在mongoose中,更新现有项目的最简单方法是使用.findOne()并在回调函数中根据需要更改对象然后调用.save()

发布评论

评论列表(0)

  1. 暂无评论