Node.js Express Save Data from Html Form to Database

Save/insert data from html form into MySQL database in node js express app; In this tutorial, i am going to show you complete guide on how to insert data from a form into database using node js express app.

In this how to insert data from a form into database using node js express tutorial; i will create a simple html markup form for display contact us form with some fields. Then submit form contact us form to handle request on routes and insert data into MySQL database using node js express app.

The how to insert data from a form into database using node js express will looks like:

How to Insert/Save Data from Html Form to Database in Node.js Express

  • Step 1 – Create New Node Js Application
  • Step 2 – Create Table in Database
  • Step 3 – Install Express EJS, Session, Body Parser, Flash
  • Step 4 – Create Route
  • Step 5 – Connect App to Database
  • Step 6 – Import Dependencies in App.js
  • Step 7 – Create HTML Markup Form

Step 1 – Create New Node Js Application

Open your command prompt and execute the following command on it to create a new node js application:

mkdir test-app
cd test-app

Step 2 – Create Table in Database

Open your phpmyadmin and execute the following query to create contacts table into your database:

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL,
  `f_name` varchar(100) NOT NULL,
  `l_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `message` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Step 3 – Install Express EJS, Session, Body Parser, Flash

Install Express EJS, Session, Body Parser, Flash into your node js express application by executing the following command on command prompt:

Flash Messages for your Express Application. Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
npm install -g express-generator
npx express --view=ejs

npm install

npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install mysql --save
  • body-parser – Node.js request body parsing middleware which parses the incoming request body before your handlers, and make it available under req.body property. In other words, it simplifies the incoming request.
  • Express-Flash Flash Messages for your Express Application. Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
  • Express-Session Express-session – an HTTP server-side framework used to create and manage a session middleware.
  • Express-EJS EJS is a simple templating language which is used to generate HTML markup with plain JavaScript. It also helps to embed JavaScript to HTML pages
  • Mysql an open-source relational database management system (RDBMS).

Step 4 – Create Route

Create Routes; So go to your node express js app root directory and open your routes directory. Then open index.js file and add following routes into it:

var express = require('express');
var router = express.Router();
var db=require('../database');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('contact-us', { title: 'Contact-Us' });
});

router.post('/contact-us', function(req, res, next) {
  var f_name = req.body.f_name;
  var l_name = req.body.l_name;
  var email = req.body.email;
  var message = req.body.message;

  var sql = `INSERT INTO contacts (f_name, l_name, email, message, created_at) VALUES ("${f_name}", "${l_name}", "${email}", "${message}", NOW())`;
  db.query(sql, function(err, result) {
    if (err) throw err;
    console.log('record inserted');
    req.flash('success', 'Data added successfully!');
    res.redirect('/');
  });
});

module.exports = router;

The file above routes/index.js file is containing two routes; i will describe as below:

  • GET /contact-us Route – This will display contact us form
  • POST contact-us Route – This will insert contact us form data into mysql database and redirect to contact us form with success flash message.

Step 5 – Connect App to Database

Connect your node express js app to database; so go to your app root directory and create database.js file and then add the following code into it:

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'my-node' // // Replace with your database Name
}); 

conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
});
module.exports = conn;

Step 6 – Import Dependencies in App.js

Import installed dependencies in app.js file; so go to your app root directory and open app.js file and import all the installed dependencies as shown below:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({ 
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))

app.use(flash());

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Step 7 – Create HTML Markup File Upload

Create html markup for file upload form; so visit your app root directory and open views directory. Then create create index.ejs file and add the following code into it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Node.js Express Save Data from Html Form to Mysql Database - Laratutorials.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container mt-4">
      <div class="card">
        <div class="card-body">
          <% if (messages.success) { %>
              <p class="alert alert-success m2-4 mb-2"><%- messages.success %></p>
          <% } %>  

          <h2>Node.js Express Save Data from Html Form to Mysql Database - Laratutorials.com</h2>

          <form action="contact-us" method="POST">
            <div class="form-group">
              <label for="firstName">First Name</label>
              <input type="text" class="form-control col-lg-9" id="f_name" aria-describedby="emailHelp" placeholder="Enter first name" name="f_name">
            </div>
            <div class="form-group">
              <label for="lastName">Last Name</label>
              <input type="text" class="form-control col-lg-9" id="l_name" aria-describedby="emailHelp" placeholder="Enter last name" name="l_name">
            </div>
            <div class="form-group">
              <label for="exampleInputEmail1">Email address</label>
              <input type="email" class="form-control col-lg-9" id="exampleInputEmail1" aria-describedby="emailHelp" name="email" placeholder="Enter email">
            </div>        
            <div class="form-group">
              <label for="exampleInputEmail1">Message</label>
              <textarea name="message" class="form-control col-lg-9"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
    </div>
  </div>
  </body>
</html>

Open your command prompt and execute the following command to run node js express file upload application:

//run the below command

npm start

Finally Open your browser and hit the following url on it:

http://localhost:3000/

Conclusion

How to Save/insert data from html form into MySQL database in node js express app; In this tutorial,you have learned how to insert data contact us from data into MySQL database using node js express app.

Recommended Node Js Tutorials

Leave a Comment