Skip to main content

Example of Create

1. Let's create an endpoint to insert 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 } = 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
		const createUser = await connection
			.promise()
			.query(
				`INSERT INTO users (username, password, email) VALUES ('${username}', '${password}', '${email}')`
			);
		// Return success if the data is inserted
		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 = 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

  • You will see the result like this.

Screenshot 2024-04-25 134858.png

****Remark - HTTP Methods 👇🏻

-END-