Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

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.

Answer №1

The issue arose when I mistakenly utilized res.redirect("/").

(My assumption is that in this scenario, the application failed to receive a response from the server, resulting in a 404 error)

Resolution:

Replace res.redirect("/") with

res.send("some different message")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Javascript object attributes

Could you retrieve the value of one object property based on the value of another property? For instance, in an SQL query, is it possible to fetch the id from the object where the object.name equals "somename"? I am trying to obtain the id of a particula ...

Using JavaScript to display a selection of objects from an array: showcasing x out of x items

What is the most efficient method for sorting or querying an array of objects using JavaScript? For example, how can I retrieve only the first two objects, followed by the next two, or obtain 5 objects starting from the 5th position? Which specific functi ...

"Utilizing the __proto__ property in Express.js for handling request

One issue that I've encountered is with the request.body generated by the express.urlencoded() middleware. Sometimes, it adds "__proto__" at the end of the request.body object, which makes it impossible to directly use it to initialize a mongoose mode ...

Introducing a pause in the function while rendering objects

After inserting setInterval into the code, it is causing all lasers to be delayed by one second. I am looking to have them fired in this order: - initially fire laser1 and laser2. - then take a 1-second break before firing another set of lasers, a ...

Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Click on the next tab within the ExtJS tab menu

I am looking to deactivate a tab and if it happens to be active, I want the system to automatically switch to the next tab. I attempted myPanel.tab.disable(); if(myPanel.tab.active) myPanel.NextSibling().tab.setActive(); and myPanel.tab.disable(); ...

Differentiating categories in the second parameter for controller method in AngularJS?

As a newcomer to Angular, I have noticed that the locals argument in the controller function can sometimes be just a function and other times an array. angular.module('contentful').controller( 'FormWidgetsController', ['$s ...

The Jquery function is failing to retrieve data from the MySQL database

I am currently attempting to retrieve values from phpMyAdmin and populate them into the second select field based on the selection made in the first select field. However, I seem to be encountering an issue as the selected value is not being passed to my P ...

Error in Typescript index: iterating over properties of a typed object

My scenario involves an interface that extends multiple other interfaces from an external library: interface LabeledProps extends TextProps, ComponentProps { id: string; count: number; ... } In a different section of the codebase, there is an ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

Transmitting POST form information from an AngularJS client to an Express/Node.js server

I am currently facing an issue where the data from my AngularJS form is not reaching the Express server, despite the client function executing successfully. I suspect there might be a problem with the URLs being used. Snippet from my AngularJS controller: ...

Displaying conflicts in a single page by clicking on a checkbox

When I click on the <thead> checkbox of the first Table, it also checks the 2nd Table checkbox. However, that is not what I need. When I click on the First thead checkbox, all checkboxes in the first Table should be checked. Also, when I click on Fi ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Is there an issue with Vue-router 2 where it changes the route but fails to update the view

I am currently facing an issue with the login functionality on a website that utilizes: Vue.js v2.0.3 vue-router v2.0.1 vuex v0.8.2 In routes.js, there is a basic interceptor setup router.beforeEach((to, from, next) => { if (to.matched.some(record ...

Mongoose and Next.js: Encountered Runtime Error - Cannot Access Undefined Properties (Token)

For some reason, the Model I defined is not working properly, despite being similar to another one that works without errors. Can anyone help me figure out why? If you need to see a minimal, reproducible example, check it out here. The problematic code: ...

Using fancybox to send an ajax post request to an iframe

Can you send a variable to the iframe when using fancybox? This is my current setup: function fancyBoxLoad(element) { var elementToEdit = $("#" + $(element).attr("class")); var content = encodeURIComponent($(elementToEdit).oute ...

How can we identify all the foreign_key1 ids from a MySQL join table that have a specific foreign_key2 assigned to them that is within a specified list?

I have a scenario where I have two tables, Table A and Table B, connected by a many-to-many relationship. Table A: ID --- 1 2 3 Table B: ID --- 4 5 6 7 Table AB: ID | A_ID | B_ID ---------------- 8 | 1 | 4 9 | 1 | 5 10 | 1 | 6 11 | 1 | 7 ...

Update the HTML page when switching between tabs

Currently, I am experiencing an issue with tab navigation in HTML. Within my code, I have two tabs named #tab1 and #tab2, each containing a form. The problem arises when I input data into #tab1, switch to #tab2, and then return to #tab1 - the information I ...