无法提出删除请求(帮助)

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

所以我正在创建一个api(没有数据库),现在我正在准备发出GET、POST和DELETE请求,当发出GET和POST请求时它工作得很好,但是当我添加我想要删除的spacidic项目的id时,邮递员给了我一个“无法删除/api/write/Avv8RZNxm”(“Avv8RZNxm”是id)错误。我也console.log编辑了它,并且id确实显示在我的控制台中。我正在使用邮递员检索响应。

import express from "express";
import shortid from "shortid";
import cors from "cors";

const app = express();
app.use(express.json());
app.use(cors());

const PORT = 4000;

let channels = [];
const lessons = [];

app.get("/", (req, res) => {
  res.json({ hello: "WORLD" });
});

app.get("/hello", (req, res) => {
  res.json({ hello: "Future senior dev" });
});

app.post("/api/write", (req, res) => {
  const channelInfo = req.body;
  channelInfo.id = shortid.generate();
  channels.push(channelInfo);
  // res.status(201);
  console.log(channelInfo);
  try {
    const response = channelInfo;
    res.status(200).json({ response });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: error.message });
  }
});

app.get("/api/write", (req, res) => {
  res.status(200).json(channels);
});

app.delete("/api/channels/:id", (req, res) => {
  const { id } = req.params;
  // console.log("ID to delete:", id);
  // console.log("Channels before DELETE:", channels);

  const deleted = channels.find((channels) => channels.id === id); //go into this array (channels) find and return to me the channel where the channel id in the array matches the one we passing in on tthis (line 42)req.params and stick it in this variable(this line)
  if (deleted) {
    console.log(deleted);
    channels = channels.filter((channels) => channels.id !== id); //!==(is not equal) //return to us a brand new channels array minus the id of the one we passed in here (app.delete("/api/channels/:id", (req, res) =>)
    res.status(200).json(deleted);
  } else {
    console.log(deleted);
    res
      .status(404)
      .json({ message: "Channel you are looking for does not exist" }); //else say hey i cant find it
  }
});

app.listen(4000, () => {
  console.log(`\n Server Running on http://localhost:${PORT}`);
});

我尝试更改代码,使用 re.body 而不是 re.params ,尝试在 catch 语句中使用 if else 语句,但没有任何效果。

api error-handling postman
1个回答
0
投票

您正在向 Postman 中的错误端点发送

delete
请求。应该是:

/api/channels/Avv8RZNxm
© www.soinside.com 2019 - 2024. All rights reserved.