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

Time:07-07

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:

    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.

CodePudding user response:

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"
});
  • Related