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

Having trouble loading mtl file in Three.js with map_ks and bump instructions?

I am currently working with an MTL file that contains the following specifications: newmtl blinn_backSG illum 4 Kd 0.17 0.15 0.28 Ka 0.00 0.00 0.00 Tf 1.00 1.00 1.00 bump -s 0.1 0.1 canvas_specular.tif -bm 0.025 Ni 1.00 Ks 0.00 0.00 0.00 map_Ks -s 0.1 0.1 ...

Modifying modal content disrupts AJAX events

When using jquery-ujs for ajax requests with data-remote="true", I encounter an issue where the first request goes smoothly but subsequent ones break. It seems that when certain events like $('#modal').empty(), $('#modal').tex ...

Tips for passing a timestamp to a Postgresql DB using a Button in a Form instead of a traditional rails time_select box

I am currently developing a CAD App in Rails 4 with Ruby 2. The goal is to provide users with a button on the screen to log an on-scene time and clear scene time, especially since most users will be using touch screen computers. Instead of using the defaul ...

Tips for positioning a highcharts pie chart and legend in the middle of a page

I'm struggling to center my highchart data in a node/react single page application. Currently, it appears off-center like this: https://i.stack.imgur.com/ccR6N.png The chart is floating to the left and I would like to have everything centered within ...

What is the best way to find a specific string within an array of strings?

I have a list of tasks as strings: todo=[ 'Get up', 'Brush my teeth', 'Go to work', 'Play games' ]; I am attempting to compare it with this: Template: <input (input)="checkArrays($event)" /> In my ...

What is the best method for retrieving all input fields within a form that are of the types text, password, file, textarea, and selectbox?

Is there a way to retrieve all input fields of specific types within a form using jQuery? jQuery("#signup-form").find('input').each(function(index, element) { }); I am aware that I can target text boxes with: jQuery("#signup-form").find(&apos ...

Is there a way to detect when the browser's back button is clicked?

As I work on supporting an e-commerce app that deals with creating and submitting orders, a user recently discovered a loophole wherein they could trigger an error condition by quickly pressing the back button after submitting their order. To address this ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

What could be preventing me from successfully calling the JavaScript AJAX function in this particular situation?

Here is my code snippet from a smarty template: <form name="transaction_form" id="transaction_form"> <table class="trnsction_details" width="100%" cellpadding="5" > <tbody> <tr> ...

What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class? I've come across tutorials tha ...

Manipulating the value of an array obtained from an API alters its data when trying to log it in the render function of a React TSX component

My program can fetch data from an API I created using a component that interacts with the backend: import React, { Fragment, useEffect, useState } from 'react' import { Button, Stack } from '@mui/material'; import TabsComponent from &ap ...

Having difficulty toggling checkboxes within a grid using the select all feature

In order to toggle checkboxes for a specific column within a grid, I encountered an issue within the JS "onUPCSelectAll" function with the eval statement displaying the following error message: JS runtime error: Object doesn't support property or meth ...

What is the best way to address cookie issues while working on a full stack application that utilizes Vue and Express.js?

Developing a full stack application requires me to use Vue on port 5173 and Express on port 3000. One issue I face is the inability to store credentials in the frontend for backend communication during development. This challenge can be addressed by servin ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

The module '../xcode' could not be located. This issue is occurring within React Native and Expo CLI, where the required stack cannot

Trying my hand at creating my first project using React Native in iOS with expo.io, I encountered an error when running the command "expo start": https://ibb.co/f2xsmpN https://i.sstatic.net/Uyxkk.png Despite attempts to reinstall and update Xcode, usin ...

Troubleshooting: Difficulty with jQuery script to change images

I am trying to modify the src attribute of an img tag using the code below, but it doesn't seem to be working. Can anyone help me figure out what's wrong? <img id='logo_image'/> <span onclick='$(logo_image).attr("src", "i ...

Guide on adding an item to the end of an array with an arrow function

const appendElement = (item) => { return (list) => { }; }; Add a new item to the end of the list. Parameters item (any): The item to add. Output (Array) => Array: Generates a closure that duplicates the original list with the added ite ...

Next.js: Uh-oh! Looks like we've hit an obstacle with Error 413 Request Entity

I've encountered an issue while attempting to upload large files using Next.js. I've set up an onChange function for my file input, and here's the code snippet: const handleFileUpload = () => new Promise(async (resolve) => { if(ref ...

Tips on saving the background image URL value into a variable

How can I save the URL value of a background image in a variable? For example: image: url(images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg); I store this value as value = images/9XkFhM8tRiuHXZRCKSdm_ny-2.jpg in a variable and then use this variable in an href tag. ...