Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method.
The issue arises when attempting to make a DELETE request using axios, resulting in a
Request failed with status code 404
error message.
Sample Request:
DELETE http://localhost:9999/item/123
;
Complete error from 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: "" }
(Note that the error does not include the part item/123
, which is puzzling)
I understand that Error 404 typically indicates a file or document not being found, often due to an incorrect route path. However, it seems like this may not be the root cause in my scenario.
Focusing on the code
Vue.js; within the file MEVN_testing/src/App.vue
, the segment containing the DELETE request appears as:
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));
In this context, the intention is to send a DELETE request to the server using the URL template
http://localhost:9999/item/item_id
Express.js; in the file
MEVN_testing/server/src/routes/routes.js
, where the DELETE request handler resides:
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;
In this snippet, the objective is simply to delete an item with a specified id from the MongoDB database.
Express.js; within the file MEVN_testing/server/src/index.js
, during app creation:
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);
// Serving built Vue app as static files at route /
app.use("/", express.static(path.join(__dirname, "..", "..", "dist")));
// Utilizing routes and associating them with the /item route
app.use("/item", require("./routes/routes.js"));
console.log(url);
app.listen(PORT);
In the code block above, by incorporating
app.use("/item", require("./routes/routes.js"))
, I am essentially linking the routes.js
file and specifying that all paths within that route should start with the address /item
.
What potential factors could be contributing to this problem? Thank you.