Home > Blockchain >  Delete user endpoint using Fetch
Delete user endpoint using Fetch

Time:04-19

I am building a user website, where the admin should be able to delete users. My project is build using Azure SQL database. I have in my controllers file, come up with an endpoint deleteUser

deleteUser

const deleteUser = (req, res) => {
  sql.connect(config, function (err) {
    if (err) console.log(err);
    // create Request object
    var request = new sql.Request();
    // query to the database and get the records

    const { id } = req.query

    request.query(
      `DELETE FROM users where User_ID = '${id}'`,
      function (err, recordset) {
        if (err) {
          console.log(err);
        } else if (!id) {
          res.json("Please provide an ID")
        } else {
          res.json(`User with ID: ${id} has been deleted!`)
        }
      }
    );
  });
};

I am then trying to make a call to this endpoint using fetch and EJS.

My code in EJS script tag

<script>

document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {

    e.preventDefault();

    fetch('http://localhost:3000/deleteUser', {
    method:'DELETE',
    headers: {
        "Content-Type": "application/json",
      },
      body: null
    })
    .then((response) => console.log(response))
    .catch((e) => {
        console.log(e)
    })
})
</script>

I console log the response, so the route must be good, but it seems as it doesn't parse the ID into the fetch. What is the right way to approach this?

Thanks in advance!

CodePudding user response:

Should the id not be in the URL of the fetch request? You are asking for the id from the request params, so it should probably be appended to the path like

const id = wherever your id comes from; 

fetch('http://localhost:3000/deleteUser?id=${id}...'

You'll need to get the user's id in your button method as well, but would need more of your code to see where that comes from.

CodePudding user response:

Usually using an ID for deletion is best approach

fetch('http://localhost:3000/deleteUser/:id...'

However, you can pass id in anyway in body, params, query or even headers)

  • Related