Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have more than one app.post function to the same route or something like that? express()

So I am trying to have more than one app.post function. To be more specific, I have a function on my client JavaScript which is requesting the server JavaScript to add content to a database, I am doing this with the app.post function. Now the thing is, if I want to delete something from the db, my client has to request that and is also sending the ID of the object which is supposed to get deleted. But my first app.post function is just for adding things to the db.

Server-side JavaScript:

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

Client-side JavaScript:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

So my question is how can I achieve that I can tell the Server which object he has to delete? I know how to delete content from the db, but I don’t know how to send this instruction from my client to the server.

>Solution :

Use a DELETE request handler with 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);
  }
});

The client side code would look like the following

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading