VueJS, expressJS, axios DELETE error: Request failed with status code 404

Issue

I am learning basics of making MEVN stack application and have some issue with axios DELETE request.

The problem is, that when I make DELETE request with axios, it gives Request failed with status code 404.

Request example: DELETE http://localhost:9999/item/123;

Full error in inspector:

XHR DELETE http://localhost:9999/ [HTTP/1.1 404 Not Found 5ms]

Object { message: "Request failed with status code 404", 
         name: "AxiosError", 
         code:         "ERR_BAD_REQUEST", 
         config: {…}, 
         request: XMLHttpRequest, 
         response: {…}, stack: "" }

(Notice, that in the error I have no part item/123, I don’t know why)

I know, that Error 404 means that file/document not found and in most cases problem in incorrect route path. It seems, that i have not the last one.

To the code

vue js; file MEVN_testing/src/App.vue, part with DELETE request:

DeleteItem(item) {
  axios
    .delete(`http://localhost:9999/item/${item.id}`)
    .then((res) => {
      console.log("DELETE request done...", res.status);
      this.UpdateList();
    })
    .catch((err) => console.log(err));

Here I want to make DELETE request to server with URL template http://localhost:9999/item/item_id

express js; file MEVN_testing/server/src/routes/routes.js, DELETE request handler:

const express = require("express");
const router = express.Router();

const itemModel = require("../models/itemModel.js");

...

router.delete("/:id", (req, res) => {
    itemModel.findOneAndDelete({ id: req.params.id });
    res.redirect("/");
});

...

module.exports = router;

Here I just want delete item with given id from mongodb database.

express js; file MEVN_testing/server/src/index.js, creating app:

const path = require("path");
const express = require("express");

const PORT = 9999;
url = `http://localhost:${PORT}/`;

const urlencodedParser = express.urlencoded({ extended: false });

const app = express();

app.use(express.json());
app.use(urlencodedParser);

// Including build vue app as static files to route /
app.use("/", express.static(path.join(__dirname, "..", "..", "dist")));
// using routes and bind it to route /item
app.use("/item", require("./routes/routes.js"));

console.log(url);
app.listen(PORT);

In the last one app.use("/item", require("./routes/routes.js")) I "including" routes.js file and defining all paths of that route to begin with /item address.

What can cause this problem?
Thank you.

Solution

The problem was, that I used res.redirect("/").

(I suppose, that in this case, the application doesn’t get a response from server, which causes an 404 error)

Solution:

replace res.redirect("/") with res.send("some message")

Answered By – rayxxx

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published