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);
},

https://i.sstatic.net/3s5Fj.png

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

When refreshed using AJAX, all dataTable pages merge into a single unified page

I followed the instructions on this page: How to update an HTML table content without refreshing the page? After implementing it, I encountered an issue where the Client-Side dataTable gets destroyed upon refreshing. When I say destroyed, all the data ...

Is it possible to obtain Ionic components without relying on Angular?

I am looking to develop an application using Ionic and VueJS. I am interested in incorporating Ionic components into Vanilla JavaScript - is there a library or resource available for this? ...

Discovering a particular string within a jQuery array object: Tips and tricks

One thing that is confusing me is the jQuery array object. To explain further: I have two arrays, one called brandsLink and the other called floorLink. When a user clicks on a link, I am saving the brand name in a variable called brandName, and then checki ...

Tips for creating multiple popups using a single line of JavaScript code

I am new to JavaScript and I am attempting to create a popup. However, I am facing an issue in opening two divs with a single line of JavaScript code. Only one div opens while the other remains closed despite trying various solutions found on this website. ...

What is the best way to separate the back-end and front-end on a single domain?

I have developed my application using React and Node.js (Express) and I am hosting it on Heroku. I am hosting it under the same domain to ensure proper cookie functionality as I encountered some issues in the past. The problem arises when I navigate to www ...

Incorporating a basic search feature into Ajax

At the moment, only results appear when you modify the query. I want to modify this to allow user input. I have set up the fields, but I need help adjusting my ajax code to accept the new search criteria which is crucial for functionality. This is what m ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

Having trouble with my Angular subscription - not behaving as I anticipated

I am facing an issue on my shop page where I have a FilterBarComponent as a child component. On initialization, I want it to emit all the categories so that all products are rendered by default. However, on my HomePageComponent, there is a button that allo ...

Exploring ways to overlay 2D text onto my Blender-created 3D model

Having created a 3D model with Blender, I am trying to overlay 2D text over the different meshes of the model. While I have successfully changed the colors of the meshes based on their indices using diffuse.color, I am struggling to draw text over my mesh. ...

Discovering the root cause of why a particular CSS style is not being implemented correctly

Currently, I am in the process of developing a secondary theme for one of my websites. It's going to be a dark theme. I'm facing an issue where a specific CSS style is not being applied to a particular element, even though it works perfectly fine ...

Error: The function styles$1.makeStyles is not defined

Currently, I am experimenting with rollup for bundling. However, when I run the code, I encounter the following problem: https://i.stack.imgur.com/8xLT3.png import { makeStyles } from '@material-ui/styles'; const styles = makeStyles({ subHead ...

Building hierarchical comments in React Native

I'm currently involved in a React Native project that includes a Nested comment section. These comments are retrieved as JSON data and displayed using a FlatList. const App = () => { const [isLoading, setLoading] = useState(true); const [data, ...

Make sure to update the package.json file at multiple locations following the execution of the "npm i" command

My goal is to automatically detect any newly installed packages based on my package.json file. This way, whenever I run "npm i", the new package will be added not only to the usual "dependencies" section but also to a custom section called "extDependenci ...

Ways to include "working hours" if statement a particular holiday dates are specified

Trying to update the code for an "if statement" to include specific dates that are official holidays when the business is not operational. The current code works if the day falls on Mon, Tue, Wed, Thu, or Fri and the time is between 09:00 and 15:00 in a 24 ...

Example of a simple router template without URL access

I am currently working on a basic example of react router with two simple routes, greetings and signup, set up within a template. Everything seems to be loading fine without any errors, but when I manually enter the /signup route in the address bar, I enco ...

Construct a new array within a JavaScript constructor function

I have been working on setting up a constructor and trying to initialize an array inside the object that will be created. This specific array is meant to hold multiple objects. function Cluster3DObject(name){ this.name = name; ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

Vue component does not display FabricJS image

Currently, I am facing an issue where I want to manipulate images on a canvas using FabricJS inside a VueJS app. In the view component, there is a prop called background which I pass in and then use fabric.Image.fromURL() to load it onto the canvas. Howeve ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Having trouble setting up Nuxt with Typescript integration

I am venturing into the world of Typescript with Nuxt (version 2.6.1) for the first time. After creating a new project using create-nuxt-app, I followed the official guide for Typescript Support. npx create-nuxt-app my-first-app cd my-first-app npm instal ...