Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" and there is no request payload being sent.

Express route.delete

    router.delete('/favorites/:favoriteId', (req, res) => {
    res.status(200).send(Number(req.params.favoriteId));
  });

Vuex service

 /**
 *
 * @param {*} favouriteId number
 */

export async function deleteUserFavourites(favouriteId) {
    const response = await http.delete('favorites',favouriteId);
    return response;
}

vuex actions

async removeFavorites({ commit }, payload) {
    const favourites = await service.deleteUserFavourites({
        id: payload.favouriteId
    });
    commit('removeFavorites', favourites);
},

Component Action Trigger

async handleListClick(item) {
            console.log(item.id);
            await this.removeFavorites({
                id: item.id
            });
        }
    }

The issue manifests in the API response:

server.js

    const path = require('path');
const fs = require('fs');
const express = require('express');
const webpack = require('webpack');

// Express Server Setup
const server = express();
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.use(express.static('public'));

// Webpack HMR
const webpackConfig = require('./webpack.config.local');
const compiler = webpack(webpackConfig);
const webpackDevMiddleware = require('webpack-dev-middleware')(
    compiler,
    webpackConfig.devServer
);
const webpackHotMiddleware = require('webpack-hot-middleware')(compiler);
server.use(webpackDevMiddleware);
server.use(webpackHotMiddleware);

// Server Startup
server.listen(3000, () => {
    console.log('*****************************************');
    console.log('*****************************************');
    console.log('** Server is listening at PORT 3000. ****');
    console.log('** http://localhost:3000/      ****');
    console.log('*****************************************');
    console.log('*****************************************');
});

// Mock APIs
const router = require('express').Router();
const routesPath = path.join(__dirname, './routes');
const filenames = fs.readdirSync(routesPath);
filenames.forEach(file => {
    if (file.endsWith('.js')) {
        console.log(`route ${file} loaded`);
        router.use('/', require(path.join(routesPath, file)));
    }
});
server.use('/api', router);

// Vue entrypoint
const template = require('./template');
server.get('/**', (req, res) => {
    const page = template();
    res.header('Content-Type', 'text/html').send(page);
});

Answer №1

When accessing your api endpoint, which is '/favorites/:favoriteId', it's important to include the favoriteId at the end of the request URL instead of in the body. Your request should look something like this:

export async function removeUserFavourite(favouriteId) {
const result = await http.delete('favorites/' + favouriteId.toString());
return result;

}

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

Click to stay in the background

I am currently facing an issue where opening a new tab on click redirects the focus to the child window instead of staying in the current window. I would like the popup to open without blocking and allowing me to maintain focus on my current window. The c ...

Chrome is experiencing a problem with anchor tags that have an href attribute set to a "blob:" URL and using a target of "_blank"

My current project involves developing a website feature that allows users to download a PDF version of a page. To achieve this, the generated HTML is rendered into a PDF on the server, which is then returned as a Base64-encoded PDF. This data is converted ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

Automatic suggestions for my personalized npm module (written in ES6/Babel) in Webstorm

When I utilize the material-ui package in Webstorm, I am able to experience helpful auto-completion using the ctrl+space shortcut: https://i.stack.imgur.com/Pivuw.png I speculated that this feature may be attributed to the inclusion of an index.es.js fil ...

Django Vue3 encounters access-control-allow-origin restriction

I am currently working on a Django rest-api project that uses Vue on the front-end. Unfortunately, I encountered an error while making requests via Vue: Console output: The following error is displayed: Access to XMLHttpRequest at 'https://api.iyziw ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...

Creating a dynamic JSON structure from an array list of elements: A step-by-step guide

I am faced with the task of transforming an array of employee IDs, listed as follows: empIds: [38670, 38671, 38672, 38673], into a JSON payload structured like this: { "members": [ { "EmployeeId": &quo ...

Refresh the page before the conclusion of the express-Node js function

I am encountering an issue with a function that functions properly with small files but fails when dealing with large files. The problem occurs when the axios post request in Express JS ends, causing a page refresh. I am using React JS on the client side a ...

Using jQuery to attach events and trigger them

Within my code, I have the following scenarios: $("#searchbar").trigger("onOptionsApplied"); And in another part of the code: $("#searchbar").bind("onOptionsApplied", function () { alert("fdafds"); }); Despite executing the bind() before the trigge ...

Images with fadeIn-Out effect on a slide restrict the movement of the div

I am currently working on a project where I have a div named "background" containing 4 images (400x300px) that fade in and out in a row every x seconds. The issue I am facing is that these images are displaying on the top-left of the browser, and I am tr ...

The mysterious force of 'undefined' is causing havoc in the promise tree

My current project involves a Node.js/Express application. One of the key functions within this codebase is responsible for handling user registration from a form submission. This function goes through various steps such as sanitizing input data, checking ...

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

Is there a way to access an Excel file with JavaScript without relying on the ActiveX control?

Is there a way to access an Excel document using JavaScript code without relying on an ActiveX control object such as shown below: var myApp = new ActiveXObject("Excel.Application"); myApp.workbooks.open("test.xls"); ...

An Axios request will consistently return a HTTP status code of 200

I have encountered an issue with a PUT request I am making. Despite receiving a 404 response from my express server, axios always sees it as 200. The correct response is shown in the express logs: PUT /v1/org/password/reset 404 339.841 ms - 71 This is th ...

Data not being properly set in the form

Check out this chunk of HTML code: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> function getCords(){ ...

Instead of relying on Vue TypeScript, we are leveraging IntelliJ with TypeScript 5.0.3 to compile our Vue project

My current version of IntelliJ IDEA is 2023.1 (Ultimate Edition) Build #IU-231.8109.175, released on March 28, 2023. I am facing an issue where my project fails to compile using "Vue TypeScript", resulting in some type mismatches being overlooked. In the ...

Exploring the functioning of mongodb connection with simultaneous requests in NodeJS express servers

As a beginner with mongoDB, I am currently working on integrating it with a Node express server. One query that has been bugging me is how to handle concurrent requests to the mongodb for reading collection data using the mongoose driver module. To illust ...

Increasing space at the top with heading

As I scroll down, the header on my website remains in a static position and disappears. However, when I scroll back up, the header reappears wherever the user is on the page. While this functionality works well, I have noticed that as I scroll all the way ...

What is the method for specifying a JSON object within a DOM element's `data` attribute?

In an attempt to store JSON data within a dataset attribute, I encountered the following HTML structure: The appearance of the HTML is as follows <div data-switch="true" data-json="{'key1': 'value 1'}, {'key2': 'valu ...