使用 Axios 在我的 CRUD 应用程序中更新博客时遇到问题 - 出现 404 错误

问题描述 投票:0回答:1

我正在为我的博客构建一个 CRUD 应用程序,并且我面临着一个特别是更新博客条目的问题。我已经成功实现了创建博客和通过 ID 检索单个博客的功能。然而,当我尝试更新博客时,我不断收到 404 错误,指示“未找到”。

这是我的handleFormSubmit 函数:

const handleFormSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.put(
        `http://localhost:4000/api/blog/${id}`,
        blog
      );
      if (response.status === 200) {
        alert("Blog updated successfully!");
      } else {
        alert("Something went wrong");
      }
    } catch (error) {
      console.error(error);
      alert("Internal Server Error");
    }
};

这是我的后端路线:

import express from "express";
import {
  getAllBlogs,
  getBlogById,
  createBlog,
  updateBlog,
  deleteBlog,
} from "../controllers/blogController.js";

const router = express.Router();

router.post("/", createBlog); // Create a new blog
router.get("/", getAllBlogs); // Get all blogs
router.get("/:id", getBlogById); // Get a single blog by ID
router.put("/:id", updateBlog); // Update a blog by ID
router.delete("/:id", deleteBlog); // Delete a blog by ID

export default router;

最初我使用Fetch API,后来改用Axios,但问题依然存在。关于如何排查和解决此问题有什么想法吗?

reactjs node.js axios crud mern
1个回答
0
投票

在您的

handleFormSubmit()
函数中,您正在调用
http://localhost:4000/api/blog/${id}
,但您没有定义与
/api/blog/:id
匹配的 PUT 路由。所以你真正想要拨打的电话是

axios.put(`http://localhost:4000/${id}`, blog)

或更新已定义的路线以匹配

/api/blog/:id
或创建新路线;哪个更适合您的需求。

© www.soinside.com 2019 - 2024. All rights reserved.