Skip to main content

Example of Create

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

Screenshot 2024-04-24 194725.png

2.  Write down using this code

const connection = require("../../services/database");
const create = async (req, res) => {
	// Get data from body
	const { username, password, email, firstname } = req.body;
	// Check if email is in the right format
	const checkEmail = new RegExp(
		/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
	).test(email);
	// Return error if the input are null or the email is not in the right format
	if (!username || !password || !email || !checkEmail) {
		return res.json({
			success: false,
			data: null,
			error: "Invalid input",
		});
	}
	try {
		//Insert the data to the database
		await connection
			.promise()
			.query(
				`INSERT INTO users (username, password, email, firstname) VALUES ('${username}', '${password}', '${email}', '${firstname}')`
			);
		// Return success if the data is inserted
		return res.json({
			success: true,
			data: {
				message: "User created successfully",
			},
			error: null,
		});
	} catch (error) {
		console.error("Error:", error);
		return res.status(500).json({
			success: false,
			data: null,
			error: error.message,
		});
	}
};
module.exports = create;

3. Go to user.js in directory routers and add the line below

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

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

module.exports = usersRouter;

4. Let's run your application again, and use postman with  localhost:5000/users/create don't forget to change the HTTP METHOD GET to POST then send the username, password and email in body with JSON

//example of JSON that we will be sending in the body
{
    "username":"john",
    "password":123,
    "email": "[email protected]",
    "firstname": "johnny"
}
  • You will see the result like this.

Screenshot 2024-04-26 015508.png

****Remark - HTTP Methods 👇🏻

-END-