我无法让这些 PATCH 和 DELETE 请求发挥作用。我尝试了很多不同的事情,PATCH 请求当前返回“无法获取/编辑/保存/1”,而删除请求返回“无法获取/删除/1”。
我还没有设置查看现有帖子的路线,因为我相信我需要将包含每个博客帖子的 div 转换为一个按钮以为其提供一个端点。
我可以创建新帖子并转到现有帖子的编辑页面。
这是我的index.js 文件中的内容:
import express from "express"
const app = express();
const port = 3000;
app.use(express.urlencoded ({ extended: true }));
app.use(express.static("public"));
app.set('view engine','ejs');
// posts
let posts = [
{
id: 1,
title: "Test Post",
copy: "Here we share our Content Guidelines and tips for success.",
},
]
// render homepage
app.get("/", (req, res) => {
res.render("index.ejs", {posts});
});
// route to view post
app.get("/:id([0-9]+)", (req, res) => {
const id = parseInt(req.params.id);
const foundPost = posts.find((post) => post.id === id);
if (!foundPost) return res.status(404).json({message: "Post not found"});
res.json(foundPost);
});
// route to create new post
app.get("/create", (req, res) => {
res.render("create.ejs");
});
// route to save new post
app.post("/save", (req, res) => {
const newPost = {
id: posts.slice(-1)[0].id +1,
title: req.body.newTitle,
copy: req.body.newCopy,
}
posts.push(newPost);
res.redirect("/");
});
// route to edit existing post
app.get("/edit/:id", (req, res) => {
const id = parseInt(req.params.id);
const foundPost = posts.find((post) => post.id === id);
if (!foundPost) {
return res.status(404).json({message: "Post not found"});
res.redirect;
} else {
res.render("edit.ejs", {foundPost});
}
});
// route to save edited post
app.post("edit/save/:id", (req, res) => {
const id = parseInt(req.params.id);
var foundPost = posts.find((post) => post.id === id);
if (!foundPost) return res.status(404).json({message: "Post not found"});
const updatedPost = {
id: foundPost.id,
title: req.body.title || foundPost.title,
copy: req.body.copy || foundPost.copy,
};
foundPost = updatedPost;
console.log(foundPost);
console.log(updatedPost);
// res.json(foundPost);
// res.redirect("/");
});
// route to delete post
app.delete("/:id", (req, res) => {
const id = parseInt(req.params.id);
const searchIndex = posts.findIndex((post) => post.id === id);
if (searchIndex > -1) {
posts.splice(searchIndex, 1);
res.sendStatus(200).json({message: "Post deleted"});
} else {
res
.status(404)
.json({ error: `Post not found. No posts were deleted.` });
}
});
app.listen(port, () => {
console.log("Listening on port " + port);
});
这是我的edit.ejs:
<%- include("partials/header.ejs") %>
<% if (locals.foundPost) { %>
<form id="editForm" method="PATCH" action="save/<%=foundPost.id%>">
<container class="new-blog">
<input class="title-box" type="text" name="title" value="<%=foundPost.title %>">
<textarea class="edit-box" id="copy" name="copy" rows="10"><%=foundPost.copy %></textarea>
<input class="btn" type="submit" value="Update">
</container>
</form>
<% } else {%>
<% return res.status(404).json({message: "Post not found"}); %>
<% } %>
<%- include("partials/footer.ejs") %>
我的 DELETE 路由在我的 index.ejs 文件中配置如下:
<a class="delete" href="/delete/<%= post.id %>">Delete</a>
我尝试过使用端点或对 PATCH 路由使用 POST 请求,但就是无法让它工作。
有人可以帮忙吗?
您提到您的 PATCH 和 DELETE 请求存在问题。以下是解决这些问题的方法:
app.patch
进行 PATCH 请求并确保正确更新 posts
数组。method-override
进行修补和删除安装
method-override
:
npm install method-override
将其包含在您的
index.js
中:
import methodOverride from 'method-override';
app.use(methodOverride('_method'));
index.js
:import express from "express";
import methodOverride from 'method-override';
const app = express();
const port = 3000;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
let posts = [{ id: 1, title: "Test Post", copy: "Here we share our Content Guidelines and tips for success." }];
app.get("/", (req, res) => { res.render("index.ejs", { posts }); });
app.get("/:id([0-9]+)", (req, res) => {
const id = parseInt(req.params.id);
const foundPost = posts.find((post) => post.id === id);
if (!foundPost) return res.status(404).json({ message: "Post not found" });
res.json(foundPost);
});
app.get("/create", (req, res) => { res.render("create.ejs"); });
app.post("/save", (req, res) => {
const newPost = { id: posts.length ? posts[posts.length - 1].id + 1 : 1, title: req.body.newTitle, copy: req.body.newCopy };
posts.push(newPost);
res.redirect("/");
});
app.get("/edit/:id", (req, res) => {
const id = parseInt(req.params.id);
const foundPost = posts.find((post) => post.id === id);
if (!foundPost) return res.status(404).json({ message: "Post not found" });
res.render("edit.ejs", { foundPost });
});
app.patch("/edit/save/:id", (req, res) => {
const id = parseInt(req.params.id);
const foundPost = posts.find((post) => post.id === id);
if (!foundPost) return res.status(404).json({ message: "Post not found" });
foundPost.title = req.body.title || foundPost.title;
foundPost.copy = req.body.copy || foundPost.copy;
res.json({ message: "Post updated", post: foundPost });
});
app.delete("/delete/:id", (req, res) => {
const id = parseInt(req.params.id);
const searchIndex = posts.findIndex((post) => post.id === id);
if (searchIndex > -1) {
posts.splice(searchIndex, 1);
res.json({ message: "Post deleted" });
} else {
res.status(404).json({ error: "Post not found. No posts were deleted." });
}
});
app.listen(port, () => { console.log("Listening on port " + port); });
edit.ejs
:<%- include("partials/header.ejs") %>
<% if (locals.foundPost) { %>
<form method="POST" action="/edit/save/<%= foundPost.id %>">
<input type="hidden" name="_method" value="PATCH">
<container class="new-blog">
<input class="title-box" type="text" name="title" value="<%= foundPost.title %>">
<textarea class="edit-box" id="copy" name="copy" rows="10"><%= foundPost.copy %></textarea>
<input class="btn" type="submit" value="Update">
</container>
</form>
<% } else { %>
<% return res.status(404).json({ message: "Post not found" }); %>
<% } %>
<%- include("partials/footer.ejs") %>
<a class="delete" href="#" data-id="<%= post.id %>">Delete</a>
<script>
document.querySelectorAll('.delete').forEach(button => {
button.addEventListener('click', async (event) => {
event.preventDefault();
const id = button.getAttribute('data-id');
const response = await fetch(`/delete/${id}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
});
if (response.ok) {
window.location.href = '/';
} else {
console.error('Failed to delete post');
}
});
});
</script>
这些更改应该可以修复您的 PATCH 和 DELETE 请求。方法覆盖的中间件允许服务器正确解释表单提交,客户端脚本通过 AJAX 处理 DELETE 请求。
欢迎通过 LinkedIn 与我联系。