Blood Bank Management System Project with Source Code | How to Create a Contact Form API in Node.js | Express, Sequelize | Part 7

Learn how to create a fully functional Blood Bank Management System using modern technologies. This step-by-step guide is perfect for both beginners and experienced developers, offering source code and practical insights. With a focus on React JS, Node JS, and Bootstrap, you'll develop an efficient system for managing blood donations, inventory, and donors. Start building your blood bank management system today!

Technologies Used

  • React JS
  • Node JS
  • Bootstrap
  • HTML & CSS

Basic Requirement

  1. Node JS
  2. Editor
  3. Web browser

How to Create a Contact Form API in Node.js | Express, Sequelize | Part 7

In this tutorial, we will learn how to create a RESTful API for managing contact form submissions using Node.js, Express, and Sequelize. This API will allow us to perform CRUD operations on contact form data.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js
  • NPM (Node Package Manager)
  • A code editor (e.g., Visual Studio Code)
  • A MySQL or PostgreSQL database

Step 1: How to install body parser

npm i body-parser
        

Step 1: Create the Contact Model

In the models/ folder, create a file called Contact.js. This will define the Contact model with columns id, name, email, subject, and message.

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = require('../db'); // Assuming you have a db.js for your database connection

const Contact = sequelize.define('Contact', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    email: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    mobile: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    message: {
        type: DataTypes.TEXT,
        allowNull: false,
    }
});

module.exports = Contact;
        

Step 2: Sync the Model with the Database

In your app.js file, ensure that Sequelize synchronizes the model with the database. This will create the table if it doesn’t already exist.

const express = require('express');
const bodyParser = require('body-parser'); 
const sequelize = require('./config/database');
const Contact = require('./models/contact');

const app = express();
app.use(bodyParser.json()); // To parse incoming JSON data
app.use(bodyParser.urlencoded({ extended: true }));

sequelize.sync()
    .then(() => {
        console.log('Database & tables synced!');
    })
    .catch(err => {
        console.error('Error syncing database:', err);
    });

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
        

Step 3: Create a POST API to Handle Form Submissions

Now let’s create a POST API to handle the submission of contact form data. In the routes/ folder, create a file called ContactRoutes.js:

const express = require('express');
const router = express.Router();
const Contact = require('../models/contact');

router.post('/contact', async (req, res) => {
    const { name, email, subject, message } = req.body;

    try {
        const newContact = await Contact.create({ name, email, subject, message });
        res.status(201).json(newContact);
    } catch (error) {
        res.status(500).json({ error: 'Failed to submit contact form' });
    }
});

module.exports = router;
        

Include this route in your main app.js file:

const express = require('express');
const bodyParser = require('body-parser');
const contactRoutes = require('./routes/ContactRoutes');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/api', contactRoutes);

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
        

Step 4: Test the POST API

Run your Node.js server:

npm start

Use Postman or any API client to test the POST request to http://localhost:3000/api/contact. Send a JSON payload with name, email, subject, and message to save the contact form data.