0

已经被这个问题困扰了两天了。尝试为故事集合实现删除功能。使用 Node js、express、mongoose、ejs 和方法覆盖。收到“无法发布”错误消息。奇怪的是,通过代码似乎与许多不同的来源(视频、文章等)相同,但不起作用。无论我尝试多少都找不到我的错误...任何帮助将不胜感激!

index.js

const express = require("express");
const router = express.Router();
const { ensureAuthenticated } = require("../config/auth");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();

const methodOverride = require("method-override");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride("_method"));


const db = require("../config/keys").MongoURI;

const Story = require("../models/Story");
const { networkInterfaces } = require("os");
const { format } = require("path");
const User = require("../models/User");
const { route } = require("./users");

// Read Page

router.get("/read", async function (req, res, next) {
  var theGenre = "";
  userId = "";

  // If URL contains genre variable then find story by theGenre
  if (req.query.genre) {
    theGenre = req.query.genre;
    theStories = await Story.find({ genre: theGenre });
  }
  // Otherwise, find all stories
  else {
    theStories = await Story.find();
  }

  // Display user name if logged in

  if (req.isAuthenticated()) {
    // Get user id from database
    userId = req.user.id;
    res.render(path.resolve("views/read"), {
      loggedIn: true,
      name: req.user.name,
      firstStory,
      theStories,
      userId,
    });
    return next();
  } else {
    res.render(path.resolve("views/read"), {
      loggedIn: false,
      name: "",
      firstStory,
      theStories,
    });
  }
});

// Delete Story

router.delete("/:id", function (req, res) {
  res.send("Delete Story " + req.params.id);
});

module.exports = router;

读取.ejs


<% theStories.forEach(function(story){ %>
<div class="story">
  <p><%= story.story %></p>
  <% if (story.auther) {%>
  <!-- Display auther name -->
  <p class="authersign"><%= story.auther %></p>
  <!-- If auther didn't not sign display 'Anonymous' -->
  <% } else { %>
  <p class="authersign">Anonymous</p>
  <% } %>
  <!-- Display genre -->
  <p class="authersign"><%= story.storyGenre %></p>
  <p class="authersign">
    <!-- Display Creation Date -->
    <% const parseDate = Date.parse(story.createdAt); %> <% var newDate = new
    Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'short', day:
    '2-digit'}).format(parseDate); %> <%= newDate %>
  </p>
  <!-- If user is logged in and user ID is the same as storyUserId then create delete button -->
  <div class="deleteButton">
    <% if (loggedIn = true && userId==story.userId) {%>
    <button onclick="document.getElementById('id01').style.display='block'">
      Delete Story
    </button>

    <div id="id01" class="modal">
      <!-- <span
        onclick="document.getElementById('id01').style.display='none'"
        class="close"
        title="Close Modal"
        >&times;</span -->
      >
      <form
        class="modal-content"
        method="POST"
        action="/theStories/<%= story.id %>?_method=DELETE"
      >
        <div class="container">
          <h2>Delete Story</h2>
          <p>Are you sure you want to delete your story?</p>

          <div class="clearfix">
            <button type="button" class="cancelbtn">Cancel</button>
            <button type="submit" class="deletebtn">Delete</button>
          </div>
        </div>
      </form>
    </div>
    <% } %>
  </div>
</div>
<br /><br />
<% }) %>

4

2 回答 2

0

您应该使用 POST 请求而不是 DELETE。HTML4 不支持 DELETE 请求。您还将方法设置为表单标签中的 POST,这就是您的代码无法正常工作的原因。

于 2020-10-25T23:51:01.683 回答
0

有效的代码:

router.delete("/:id", function (req, res) {
  Story.findByIdAndDelete(req.params.id, function (err) {
    if (err) console.log(err);
  });
  req.flash("success_msg", "Your story has been deleted");
  return res.redirect("read");
});
于 2020-11-19T23:59:36.630 回答