Home > Back-end >  Expressjs base API delete method show error can not get error?
Expressjs base API delete method show error can not get error?

Time:02-10

I'm new is Express.js; I try to build an API without any database. All routes work correctly but the post and delete API is not working. When I hit delete URL in the browser, I find an error. delete URL error

My app.js routes page look like

import express from "express";
import logger from "morgan";
import bodyParser from "body-parser";

//  get routes
import indexRouter from "./routes/index.js";
import postRouter from "./routes/post.js";
import tagRouter from "./routes/tags.js";
import commentRouter from "./routes/comment.js";
import authorRouter from "./routes/author.js";

// post routers
import postMethodRouters from "./routes/postMethodRouters.js";

//  delete routers
import deletePostRouters from "./routes/delete.js";

var app = express();

app.use(logger("dev"));
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: false }));

//  get method
app.use("/api/v1/", indexRouter);
app.use("/api/v1/post", postRouter);
app.use("/api/v1/tags", tagRouter);
app.use("/api/v1/comments", commentRouter);
app.use("/api/v1/authors", authorRouter);

//  post method
app.use("/createPost", postMethodRouters);

//  delete method
app.use("/api/v1/", deletePostRouters);

var listener = app.listen(8080, function () {
  console.log("Listening on port "   listener.address().port);
});

My delete.js routes look like

import express from "express";

var router = express.Router();

router.delete("/delete/:id", function (req, res) {
  res.status(200).send("DELETE request to homepage");
});

export default router;

My post.js routers look like

import express from "express";

import getBlog from "../API/Post/singleGenrater.js";

var router = express.Router();


router.post("/", function (req, res) {
  
  res.send("POST request to homepage");
});
export default router;

CodePudding user response:

In app.js, try to fix it like below (remove the "/" after "/api/v1")

//  delete method
app.use("/api/v1", deletePostRouters);

Second, in the file delete.js, I see that you are using the DELETE method (router.delete("/delete/:id"), but when you call the api you use it as GET (GET /api/v1/delete/id) ? It's a different method, so it won't call the api.

  • Related