Skip to main content

Example of Delete

  1. Let's create an endpoint to delete user from the database, create deleteUser.js into directory controllers->users

Screenshot 2024-04-25 162736.png

2.  Write down using this code

const connection = require("../../services/database");

const deleteUser = async (req, res) => {
	const userId = req.query.userId;
	// Check if userId is number or not
	const checkUserId = new RegExp(/^\d+$/).test(userId);
	if (!userId || !checkUserId) {
		return res.json({
			success: false,
			data: null,
			error: "Invalid input",
		});
	}
	try {
		await connection
			.promise()
			.query(`DELETE FROM users WHERE id = ${userId}`);
		// Return success if the data is deleted
		return res.json({
			success: true,
			data: null,
			error: null,
		});
	} catch (error) {
		console.error("Error:", error);
		return res.status(500).json({
			success: false,
			data: null,
			error: error.message,
		});
	}
};
module.exports = deleteUser;

3. Go to users.js in directory routers and add the line below, this time we will use delete().

const express = require("express");
const getAll = require("../controllers/users/getAll");
const create = require("../controllers/users/create");
//add this line 👇
const deleteUser = require("../controllers/users/deleteUser");
const usersRouter = express.Router();

usersRouter.get("/all", getAll);
usersRouter.post("/create", create);
//add this line 👇
usersRouter.delete("/delete", deleteUser);

module.exports = usersRouter;

4. Let's run your application again, and use postman with  localhost:5000/users/delete?userId=1 don't forget to change the HTTP METHOD POST,GET,PATCH to DELETE

  • You will see the result like this.

Screenshot 2024-04-25 163833.png

-END-