How to insert request body into a MySQL database using Express js
Last Updated :
24 Jul, 2024
If you trying to make an API with MySQL and Express JS to insert some data into the database, your search comes to an end. In this article, you are going to explore - how you can insert the request data into MySQL database with a simple Express JS app.
What is Express JS?
Express JS is a backend framework for building RESTful APIs with Node.Js, launched as free and open-source software program beneath the MIT License. It is designed for constructing web applications and APIs. It has been referred to as the de facto general server framework for Node.Js
What is MySQL?
MySQL is an open-source Relational Database Management System (RDBMS) that enables users to store, manage, and retrieve data efficiently. It is broadly used for various programs, from small-scale projects to big-scale websites and enterprise-stage answers.
Steps to insert request body in MySQL database using Express.
Step 1: Initialized an Express app using the following command
mkdir ExpressMySQLDemo
cd ExpressMySQLDemo
npm init -y
Step 2: Install the required dependencies
npm i express mysql2
Folder Structure:
Folder StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.6.5"
}
Example Code: Your final code in "app.js" should look like this
JavaScript
//app.js
const express = require("express");
const mysql = require("mysql2");
const app = express();
const bodyParser = require("body-parser");
const PORT = 3000;
// Middleware for parsing JSON
app.use(express.json());
app.use(bodyParser.json());
// Create a MySQL connection
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "my_database",
});
// Connect to the database
connection.connect((err) => {
if (err) {
console.error("Database connection failed: " + err.stack);
return;
}
console.log("Connected to the database");
});
// POST request to insert data
app.post("/insert", async (req, res) => {
// Get the request body
const reqBody = {
name: req.body.name,
rollno: req.body.rollno,
};
// Insert the request body into the database
const query = `INSERT INTO student (name, rollno) VALUES (?, ?)`;
connection.query(query, [reqBody.name, reqBody.rollno]);
// Send a response to the client
res.send("Data inserted successfully");
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 3: To setup database, you need to create a database and a table in your MySQL database, just below commands and queries in MySQL Workbench or MySQL Client:
create database my_database;
use my_database;
create table student (name varchar (30), rollno Integer (5));
Step 4: Run the app with the following command.
node app.js
Step 5: Send a POST request to the /insert route with a JSON body
For testing, you can run below "curl" command to save the data.
curl -X POST http://localhost:3000/insert -H 'Content-Type: application/json' -d '{
"name": "Ghanshyam",
"rollno": "1001"
}'
or you can make request using Postman:

Output:
Similar Reads
How to Insert and Select Data in SQLite3 Database using Node.js ? Inserting and selecting data in an SQLite3 database using Node.js involves connecting to the database, running SQL queries, and handling the results. SQLite is an excellent choice for small to medium-sized applications due to its simplicity and lightweight nature. This guide will walk you through th
3 min read
How to import data from .CSV file into MySQL table using Node.js ? What is .CSV file? The .CSV (Comma Separated Values) files are plain text files that contains a list of data separated by comma(,). It is a format best used for tabular data, row, and columns, exactly like a spreadsheet, just the difference is that the file is in the form of plain text. The idea of
4 min read
How To Make A GET Request using Postman and Express JS Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
3 min read
How to create routes using Express and Postman? In this article we are going to implement different HTTP routes using Express JS and Postman. Server side routes are different endpoints of a application that are used to exchange data from client side to server side.Express.js is a framework that works on top of Node.js server to simplify its APIs
3 min read
How to access Raw Body of a Post Request in Express.js ? Raw Body of a POST request refers to unprocessed or uninterpreted data sent in the request before Express or any middleware processes or understands it. It's like raw ingredients before the cooking begins. In this article we will see various approaches to access raw body of a post request in Express
3 min read
How to Create a Simple Server Using ExpressJS? The server plays an important role in the development of the web application. It helps in managing API requests and communication between the client and the backend. ExpressJS is the fast and famous framework of the Node.Js which is used for creating the server.In this article, we will create a simp
3 min read
How to resolve req.body is empty in posts error in Express? In Express the req.body is empty error poses a critical challenge in web development, particularly in the context of processing POST requests on the server side. This issue arises when the server encounters difficulties parsing the request body, resulting in an empty or undefined req.body object. De
4 min read
How to Connect to a MySQL Database Using the mysql2 Package in Node.js? We will explore how to connect the Node.js application to a MySQL database using the mysql2 package. MySQL can be widely used as a relational database and mysql2 provides fast, secure, and easy access to MySQL servers, it can allow you to handle database queries efficiently in Node.js applications.
6 min read
How to Create Table in SQLite3 Database using Node.js ? Creating a table in an SQLite database using Node.js involves several steps, including setting up a connection to the database, defining the table schema, and executing SQL commands to create the table. SQLite is a lightweight and serverless database that is widely used, especially in applications t
3 min read
How to Connect SQLite3 Database using Node.js ? Connecting SQLite3 database with Node.js involves a few straightforward steps to set up and interact with the database. SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine, making it ideal for small to medium-sized applications. Hereâs how you can connect an
2 min read