Is there a way to have multiple app.post functions for the same route using express()?

I'm currently exploring the idea of incorporating multiple app.post functions in my project. Specifically, I have a client-side JavaScript function that sends a request to the server-side JavaScript to add content to a database using the app.post function. However, if I want to delete something from the database, the client needs to send a request along with the ID of the object to be deleted. The challenge is that my initial app.post function is only set up for adding items to the database.

Here's a snippet of the server-side JavaScript code:

const express = require("express");
const { request, response } = require("express");
const app = express();
app.listen(3000, () => console.log("listening at 3000"));
app.use(express.static("public"));
app.use(express.json({ limit: "1mb" }));

const database = new Datastore("database.db");
database.loadDatabase();

app.get("/api", (request, response) => {
  database.find({}, (err, data) => {
    if (err) {
      console.log("An error has occurred");
      response.end();
      return;
    }
    response.json(data);
  });
});

app.post("/api", (request, response) => { //Adding Content to the db
  console.log("Server got a request!");
  const data = request.body;
  database.insert(data);
  response.json(data);
});

And here's a glimpse of the client-side JavaScript code:

    const data = { Item, ID };
    const options = {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-type": "application/json",
      },
    };
    fetch("/api", options);

My question revolves around finding a way to instruct the Server about which object to delete. While I know how to remove content from the database, I'm unsure about how to communicate this instruction effectively from the client to the server.

Answer №1

To remove data, implement a DELETE request handler using an id route parameter.

app.delete("/api/:id", async (req, res, next) => {
  try {
    res.json(await database.deleteById(req.params.id)); // ¯\_(ツ)_/¯
  } catch (err) {
    next(err);
  }
});

On the client side, the code would appear as follows:

const id = "some-id-from-somewhere";
const res = await fetch(`/api/${encodeURIComponent(id)}`, {
  method: "DELETE"
});

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

What is a method to omit elements within a nested child element from a selection without relying on the children() function

Here is an example of an element: <div id="foo"> <a href="#" class="some">click me</a> <div id="bar"> <a href="#" class="some">click me too</a> </div> </div> I am facing the challenge of selectin ...

The request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

Rails 6 not displaying Javascript as intended

I am a beginner at this, but so far everything seems to be functioning smoothly. On my page, users can upload and delete photos without any issues. The uploading and deleting processes work perfectly fine. However, I am facing an issue where the page does ...

The front end is failing to display error messages generated on the server side

When the server-side login fails, the message res.status(403).json({ fail: "Login failed" }); is passed to the frontend using setHelperText(failMessage);. How can I display the 'Login Failed' message on the frontend? An error is displayed in the ...

The issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

Is it possible to access JSON with a numeric key and receive undefined as a result?

I've been attempting to extract information from my JSON data, but I keep getting an undefined result. Here is a snippet of my JSON: { "1": "A", "2": "B", "3": "C", "4": "D", "5": "E", "6": "F", "key":"pair" } This i ...

How would you go about creating a VueJS component that displays a table with a set number of columns and automatically distributes the cells within them?

Hey there! I'm currently working with a VueJS component that looks like this: <template> <div> <table> <tbody> <tr v-for="(item, index) in items" :key="index"> <t ...

Pagination Bug: Index Incorrectly Grabbed Upon Navigating to Next Pages

I encountered an issue with my paginated article list (105 articles with 10 per page). Everything works fine on the first page, but when I click on an article from page 2 onwards, it takes me to the index of the very first article in the array. <div cla ...

Creating cookies in R Shiny: Storing variables for future use

Writing a fixed string to cookies can be done easily using methods like Cookies.set(\'cookie_2\', \'value\', { expires: 7 }) (see tutorial here). However, saving the variable user to cookie_2 may require a different ...

The Discord.js command outright declines to function

I'm having trouble with a code that I'm working on. The goal is to create a command that is enabled by default, but once a user uses it, it should be disabled for that user. However, when I try to execute the code, it doesn't work at all and ...

The code for accessing files in MongoDB using this.db.collection appears to be malfunctioning

I am facing an issue while trying to retrieve a file from MongoDB Atlas using gridfsstream and multer. The error that keeps popping up is: TypeError: this.db.collection is not a function Although I can successfully upload files, the retrieval process i ...

The MUI select box stays fixed in its position relative to both the height and width of the viewport while scrolling

Whenever I click on the MUI select, the dropdown box stays fixed in the viewport both horizontally and vertically as I scroll. Ideally, it should move along with the select. Any ideas on how to fix this issue? I attempted adjusting the positioning of the ...

Replacing a string using Regular Expression based on certain conditions

When working with a node.js server, I encountered the need to modify URL addresses using JavaScript in a specific way: For instance: hostX/blah/dir1/name/id.js?a=b --> name.hostY/dir2.js?guid=id&a=b Another example: hostZ/dir1/name/id.js --> ...

Looking for an alternative method since jQuery has deprecated the use of '.toggle()' function

After jQuery deprecated the .toggle() method, I have been searching for a new and simple solution to implement a "Read more" button that slides down a paragraph while changing text to "Read less". Below is the code I have put together: var moreText = "Re ...

Ways to showcase a list in 3 columns on larger screens and 1 column on smaller screens

When viewing on a computer, my list appears like this: https://i.sstatic.net/fNhaP.png However, when I switch to a phone, only the first column is visible and the list does not continue in a single column format. I am utilizing Bootstrap for my layout, a ...

Is it a cookie-cutter function?

Can someone help me solve this problem: Implement the special function without relying on JavaScript's bind method, so that: var add = function(a, b) { return a + b; } var addTo = add.magic(2); var say = function(something) { return something; } ...

Exhibit MongoDB collection information through PUG template (Issue: Undefined Array)

I am encountering an issue while attempting to showcase the data from my MongoDB "users" collection. I keep receiving an undefined error with the array. Within my user controller file, I have imported express, express.router, and my user model. Below is ...

Is it possible to upload a file using Angular and ASP.NET Web API Core?

I am encountering an issue with CORS policy while making requests. It works fine when the content-type is set to 'application/json'. However, when I try to upload a file using content-type 'multipart/form-data', I receive an error: XML ...

React NextJS: Unable to retrieve cookies or properties post redirection

Within my nextJS application, when a user logs in on the login page, a cookie is created with a token and then they are redirected to the main page which utilizes the main component. However, within the Main component, I am encountering an issue where the ...

The react-datepicker component is unable to set the state to the format dd/MM/yy

The date is currently shown in the correct format (31/08/21), but when onChange gets triggered, startDate changes to something like this: Tue Aug 31 2021 21:29:17 GMT+0200 (Central European Summer Time) Is there a way to maintain the display format I wa ...