Reactjs Nodejs PostgreSQL Example

Reactjs Nodejs PostgreSQL CRUD Example

In the tutorial, I introduce how to build an “React.js Nodejs CRUD PostgreSQL Example” project with the help of Ajax to POST/GET/PUT/DELETE requests with step by step coding examples:

– Nodejs project produces CRUD RestAPIs with PostgreSQL database using the supporting of Sequelize ORM.
– React.js project will consume the Nodejs CRUD RestAPIs by Ajax then show up on Reactjs component’s views.

Related posts:


– I draw a fullstack overview Diagram Architecture from React.js Frontend to PostgreSQL database through Nodejs RestAPI backend.
– Develop Nodejs CRUD RestAPIs with the supporting of Sequelize ORM.
– Implement Reactjs CRUD application with Ajax fetching APIs to do CRUD request (Post/Get/Put/Delete) to Nodejs Backend APIs.
– I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Reactjs to do CRUD requests to Nodejs RestAPIs Server and save/retrieve data to PostgreSQL database.

What will we do?


React Node.js PostgreSQL CRUD Example – Step By Step React, Nodejs and PostgreSQL simple full-stack Application

Video Guide – Reactjs Nodejs PostgreSQL CRUD Example

Overview Diagram Architecture – React Node.js PostgreSQL CRUD Example (Nodejs Reactjs CRUD Example)

Overall Architecture System: Reactjs + Nodejs + PostgreSQL

React.js Nodejs PostgreSQL Diagram Architecture
React.js Nodejs PostgreSQL Diagram Architecture
  • We build a backend: Nodejs CRUD Application with PostgreSQL that provides RestAPIs for POST/GET/PUT/DELETE data entities and store them in PostgreSQL database.
  • We implement React.js CRUD Application that use Ajax to interact (call/receive requests) with Nodejs CRUD application and display corresponding data in Reactjs Component.

Nodejs PostgreSQL CRUD Design Application

Nodejs-Build-CRUD-MySQL-Architecture-Overview
Nodejs-Build-CRUD-MySQL-Architecture-Overview

We have 4 main blocks for the application:

  • For building RestAPIs in Nodejs application, we use Express framework.
  • For interacting with database PostgreSQL, we use Sequelize ORM.
  • We define APIs URL in router.js file
  • We implement how to process each API URL in controller.js file
  • We use Bootstrap and JQuery Ajax to implement frontend client.

Reactjs CRUD Application Design

Reactjs CRUD RestAPI Application Frontend Architecture Diagram
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

– Reactjs CRUD Application is designed with 2 main layers:

    React.js components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
    Ajax is used by Reactjs component to fetch (post/put/get/delete) data from remote restapi by http request

Reactjs CRUD Application defines 5 components:

  • Home.js is used serve as the landing page for your app.
  • AppNavbar.js is used to establish a common UI feature between components.
  • CustomerList.js is used to show all customers in the web-page
  • CustomerEdit.js is used to modify the existed customer
  • App.js uses React Router to navigate between components.

Integrative Project Goal

Reactjs Home page:

Project Goal Home Page
Project Goal Home Page

Reactjs List all data:

Reactjs application show list data after update a customer
Reactjs application show list data after update a customer

Reactjs add data:

Project Goal - Reactjs Add a Customer through Nodejs RestAPI
Project Goal – Reactjs Add a Customer through Nodejs RestAPI

Reactjs update data:

Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database
Project Goal – Reactjs Update Customer through Nodejs RestAPI to MySQL database

Reactjs delete a customer with id=2, check the Customer List after deleting:

Reactjs show list customers after doing CRUD operations
Reactjs show list customers after doing CRUD operations

Check PostgreSQL Database after do CRUD operations:

Check PostgreSQL database after doing CRUD operations
Check PostgreSQL database after doing CRUD operations

How to Integrate Reactjs with Nodejs?

For starting to integrate Reactjs with Nodejs project, I recommend you a previous post with detail steps to pratice:

How to Integrate Reactjs with Nodejs Tutorial

React-project-structure
React-project-structure
Nodejs-Project-Structure
Nodejs-Project-Structure
Integrate-successfully-between-Nodejs-RestAPI-and-Reactjs
Integrate-successfully-between-Nodejs-RestAPI-and-Reactjs

Nodejs PostgreSQL CRUD RestAPIs Example – Backend Development

Now it’s time for building the “Nodejs PostgreSQL CRUD RestAPIs Example” project with a set of simple steps:

Let’s go!

How to build Nodejs PostgreSQL CRUD RestAPI project

Create Nodejs PostgreSQL project

Before creating a Nodejs project, we need to confirm that the Nodejs and npm had been installed in your computer development by cmd: node -v and npm -v

Check Nodejs environment for development
Check Nodejs environment for development

If these commandlines are not recognized by command prompt, it means you need to install them by visit the https://nodejs.org/en/ site and download installed package and do the nodejs setup for development later.

Now starting development! Create a folder and named it as Nodejs-Reactjs-postgresql, go inside the folder, open a cmd and initiate a Nodejs project by cmd npm init. After all, a package.json file is created as below content:

{
  "name": "nodejs-reactjs-restapi-example",
  "version": "1.0.0",
  "description": "Nodejs Reactjs RestAPI CRUD PostgreSQL database",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/loizenjava"
  },
  "keywords": [
    "nodejs",
    "reactjs",
    "crud",
    "postgresql"
  ],
  "author": "https://loizenjava.com",
  "license": "ISC",
  "dependencies": {
    "body-parse": "^0.1.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "pg": "^8.4.2",
    "pg-hstore": "^2.3.3",
    "sequelize": "^6.3.5"
  }
}

For coding Editor, we use friendly Visual Studio Code to write code and debug Nodejs project. For the tutorial, We will create a project with below structure:

Nodejs CRUD MySQL RestAPI project
Nodejs CRUD MySQL RestAPI project
  1. a file db.config.js is used to define PostgreSQL database configuration with Sequelize ORM
  2. a file customer.model.js is used to define a Sequelize model mapped with corresponding PostgreSQL database table schema.
  3. a file router.js is used to define all Express RestAPI URLs
  4. a file controller.js is used to implement detail logic code to process each incoming request
  5. a file server.js is used to implement a Nodejs Web server

To development a Nodejs CRUD PostgreSQL project, we need a set of packages to handle the full stack of the web backend proccessing, they includes Express framework, Cors, Body Parse, PostgreSQL packages and Sequelize ORM.

$npm install --save express cors body-parser PostgreSQL2 sequelize

Nodejs PostgreSQL Database Configuration

Firstly, we create a file env.js with an const Object to include all configured parameters for PostgreSQL database setup.

const env = {
  database: 'loizenjavadb',
  username: 'postgres',
  password: '123',
  host: 'localhost',
  dialect: 'postgres',
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
};

module.exports = env;

In the tutorial, for the main setting between PostgreSQL database and Sequelize ORM, we define a file db.config.js as below code:

const env = require('./env.js');
 
const Sequelize = require('sequelize');
const sequelize = new Sequelize(env.database, env.username, env.password, {
  host: env.host,
  dialect: env.dialect,
  operatorsAliases: false,
 
  pool: {
    max: env.max,
    min: env.pool.min,
    acquire: env.pool.acquire,
    idle: env.pool.idle
  }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;
 
db.Customer = require('../models/customer.model.js')(sequelize, Sequelize);
 
module.exports = db;

Define Nodejs Sequelize Model

We need define a Sequelize ORM Model to represent a table in the database. So here is the customer.model.js code:

module.exports = (sequelize, Sequelize) => {
	const Customer = sequelize.define('customer', {	
	  id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            primaryKey: true
    },
	  firstname: {
			type: Sequelize.STRING
	  },
	  lastname: {
		  type: Sequelize.STRING
  	},
	  address: {
			type: Sequelize.STRING
	  },
	  age: {
			type: Sequelize.INTEGER
    },
    copyright: {
      type: Sequelize.STRING,
      defaultValue: "https://loizenjava.com"
    }
	});
	
	return Customer;
}

We create a Sequelize Customer model with 6 attributes for mapping with all corresponding customers table’s columns:

  1. id attribute is a primary key with Int type (in database)
  2. firstname attribute has Sequelize.STRING type mapping with the firstname column in customers table with varchar type
  3. lastname attribute has Sequelize.STRING type mapping with the lastname column in customers table with varchar type
  4. address attribute has Sequelize.STRING type mapping with the lastname column in customers table with varchar type
  5. age attribute has Sequelize.INTEGER type mapping with the age column in customers table with int type
  6. copyrightby attribute has Sequelize.STRING type mapping with the copyrightby column in customers table with varchar type and having default value is https://loizenjava.com

Define Express RestAPIs Router – POST/GET/PUT/DELETE

We define 5 APIs:

  • /api/customer (with POST method) is used to Post a customer to PostgreSQL database
  • /api/customer/:id (with GET method) is used to retrieve a customer from PostgreSQL database with a given id
  • /api/customers (with GET method) is used to retrieve all customers from PostgreSQL database
  • /api/customer (with PUT method) is used to update a customer from PostgreSQL database
  • /api/customer/:id (with DELETE method) is used to remove a customer from PostgreSQL database

Coding:


let express = require('express');
let router = express.Router();
 
const customers = require('../controllers/controller.js');

router.post('/api/customer', customers.createCustomer);
router.get('/api/customer/:id', customers.getCustomer);
router.get('/api/customers', customers.customers);
router.put('/api/customer', customers.updateCustomer);
router.delete('/api/customer/:id', customers.deleteCustomer);

module.exports = router;

Implement RestAPIs Controller

For processing Post/Get/Put/Delete RestAPI requests, we implement controller.js with 5 functions:

  • exports.createCustomer = (req, res) is used to create a new Customer (post request processing)
  • exports.getCustomer = (req, res) is used to retrieve a Customer with a given id from PostgreSQL database(get request)
  • exports.customers = async (req, res) is used to retrieve all customers
  • exports.updateCustomer = async (req, res) is used to update a customer from PostgreSQL database
  • exports.deleteCustomer = async (req, res) is used to delete a customer from PostgreSQL database
Nodejs Post request – Add a data to PostgreSQL
exports.createCustomer = (req, res) => {
    let customer = {};

    try{
        // Building Customer object from upoading request's body
        customer.firstname = req.body.firstname;
        customer.lastname = req.body.lastname;
        customer.address = req.body.address;
        customer.age = req.body.age;
    
        // Save to PostgreSQL database
        Customer.create(customer, 
                          {attributes: ['id', 'firstname', 'lastname', 'age', 'address', "copyright"]})
                    .then(result => {    
                      res.status(200).json(result);
                    });
    }catch(error){
        res.status(500).json({
            message: "Fail!",
            error: error.message
        });
    }
}

exports.createCustomer = (req, res) gets a posting customer’s info via request.body object. Then it uses Sequelize to save the customer object to database. After done, it returns a successfully posting message. Otherwise, a error message will be returned.

Nodejs Get request – retrieve a single data from PostgreSQL
exports.getCustomer = (req, res) => {
    Customer.findByPk(req.params.id, 
                        {attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']})
        .then(customer => {
          res.status(200).json(customer);
        }).catch(error => {
          // log on console
          console.log(error);

          res.status(500).json({
              message: "Error!",
              error: error
          });
        })
}

exports.getCustomer = (req, res) retrieves a customer data from PostgreSQL database with a given id by using Sequelize ORM. After done, it returns a customer object to client. Otherwise, a error message will be returned.

Nodejs Get request – retrieve all data from PostgreSQL database
exports.customers = (req, res) => {
    // find all Customer information from 
    try{
        Customer.findAll({attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']})
        .then(customers => {
            res.status(200).json(customers);
        })
    }catch(error) {
        // log on console
        console.log(error);

        res.status(500).json({
            message: "Error!",
            error: error
        });
    }
}

The function exports.customers = (req, res) retrieves all Customer objects from PostgreSQL database.

Nodejs Delete request – delete a data from PostgreSQL with a given id
exports.deleteCustomer = async (req, res) => {
    try{
        let customerId = req.params.id;
        let customer = await Customer.findByPk(customerId);

        if(!customer){
            res.status(404).json({
                message: "Does Not exist a Customer with id = " + customerId,
                error: "404",
            });
        } else {
            await customer.destroy();
            res.status(200);
        }
    } catch(error) {
        res.status(500).json({
            message: "Error -> Can NOT delete a customer with id = " + req.params.id,
            error: error.message
        });
    }
}

The function exports.deleteCustomer = async (req, res) finds a Customer by a given id. If the customer is found, it will be deleted by destroy() function and return back client a successfully message with 200 status code. Otherwise, an error message is returned.

Nodejs Put request – update a data from PostgreSQL
exports.updateCustomer = async (req, res) => {
    try{
        let customer = await Customer.findByPk(req.body.id);
    
        if(!customer){
            // return a response to client
            res.status(404).json({
                message: "Not Found for updating a customer with id = " + customerId,
                error: "404"
            });
        } else {    
            // update new change to database
            let updatedObject = {
                firstname: req.body.firstname,
                lastname: req.body.lastname,
                address: req.body.address,
                age: req.body.age
            }
            let result = await Customer.update(updatedObject,
                              { 
                                returning: true, 
                                where: {id: req.body.id},
                                attributes: ['id', 'firstname', 'lastname', 'age', 'address', 'copyright']
                              }
                            );

            // return the response to client
            if(!result) {
                res.status(500).json({
                    message: "Error -> Can not update a customer with id = " + req.params.id,
                    error: "Can NOT Updated",
                });
            }

            res.status(200).json(result);
        }
    } catch(error){
        res.status(500).json({
            message: "Error -> Can not update a customer with id = " + req.params.id,
            error: error.message
        });
    }
}

The function exports.updateCustomer = async (req, res) finds a customer object by a given id. If the customer is found, we change the customer attributes with new values retrieving from request.body object. After done, a successfully message will be returned. Otherwise an error message will be returned.

Create Nodejs Server.js

const express = require('express');
const app = express();

var bodyParser = require('body-parser');
 
global.__basedir = __dirname;
 
const db = require('./app/config/db.config.js');

const Customer = db.Customer;

let router = require('./app/routers/router.js');

const cors = require('cors')
const corsOptions = {
  origin: 'http://localhost:4200',
  optionsSuccessStatus: 200
}
app.use(cors(corsOptions));

app.use(bodyParser.json());
app.use(express.static('resources'));
app.use('/', router);

// Create a Server
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

db.sequelize.sync({force: true}).then(() => {
  console.log('Drop and Resync with { force: true }');
  Customer.sync().then(() => {
    const customers = [
      { firstname: 'Jack', lastname: 'Smith', 
                age: 23, address: '374 William S Canning Blvd'},
      { firstname: 'Adam', lastname: 'Johnson', 
                age: 31, address: 'Fall River MA 2721. 121 Worcester Rd'},
      { firstname: 'Dana', lastname: 'Bay', 
                age: 46, address: 'Framingham MA 1701. 677 Timpany Blvd'},
    ]
    
    for(let i=0; i<customers.length; i++){
      Customer.create(customers[i]);
    }
  })
}); 

How does the server.js file work?

server.js file will create a Nodejs server’s instance listening at port 8080 and also initiate a PostgreSQL table customers with 3 records.

const express = require('express');
const app = express();
...
const server = app.listen(8080, function () {
 
  let host = server.address().address
  let port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port); 
})

– For parsing body of requests, we need use body-parser dependency, some below lines of code will be added to server.js file:

...
var bodyParser = require('body-parser');
...
app.use(bodyParser.json());
...
const server = app.listen(8080, function () {
...

We define all RESTAPI URLs in a file router.js and then need attach it with the Express Application:

...
let router = require('./app/routers/router.js');
...
app.use('/', router);
...
const server = app.listen(8080, function () {
...

Backend Testing – Nodejs PostgreSQL CRUD RestAPIs testsuite

PostgreSQL database:

Check PostgreSQL customers table right after initing
Check PostgreSQL customers table right after initing

Testcase 1 – Get all Customers

– Nodejs retrieves all customers from PostgreSQL database:

Nodejs Get request Get All Customer from PostgreSQL
Nodejs Get request Get All Customer from PostgreSQL

Testcase 2 – Create a Customer

– Nodejs posts a new customer to PostgreSQL database:

Nodejs Post request - Post a Customer to PostgreSQL
Nodejs Post request – Post a Customer to PostgreSQL

Testcase 3 – Update a Customer

– Nodejs updates a customer from PostgreSQL database:

Nodejs PUT request - Update an existing Customer from PostgreSQL
Nodejs PUT request – Update an existing Customer from PostgreSQL

Testcase 4 – Delete a Customer

– Nodejs delete a Customer from PostgreSQL database:

Nodejs Delete request - Delete a Customer from PostgreSQL database
Nodejs Delete request – Delete a Customer from PostgreSQL database

Reactjs CRUD Application Example – Frontend Development

Reactjs CRUD Application Overview with Nodejs RestAPIs

React project structure
React project structure
Reactjs CRUD RestAPI Application Frontend Architecture Diagram
Reactjs CRUD RestAPI Application Frontend Architecture Diagram

For more details, we go back to the session: Reactjs CRUD Application Overview with Nodejs RestAPIs

How to build Reactjs Application?

We build a Reactjs Application that fetchs data from PostgreSQL database through PostgreSQL RestAPI with 5 UI components. Step to do:
– Setup Reactjs Application
– Build Reactjs Navigation Bar component
– Build Reactjs Home page component
– Build Reactjs CustomerList Component
– Build Reactjs CustomerEdit Component
– Update Reactjs App.js Component with Router

Setup Reactjs Application with Bootstrap

Create React App is a command line utility that generates React projects for you. It’s a convenient tool because it also offers commands that will build and optimize your project for production.
The create-react-app will set up everything you need to run a React application.

– Create a new project in the app directory with Yarn.

yarn create react-app app

Project Structure:

React project structure
React project structure

More details you can see at: Create Reactjs Project

After the app creation process completes, navigate into the app directory and install Bootstrap, cookie support for React, React Router, and Reactstrap.

Reactstrap: This library contains React Bootstrap 4 components that favor composition and control. The library does not depend on jQuery or Bootstrap javascript.
– React Router: Components are the heart of React’s powerful, declarative programming model. React Router is a collection of navigational components that compose declaratively with your application.

cd app
yarn add bootstrap@4.1.3 react-cookie@3.0.4 react-router-dom@4.3.1 reactstrap@6.5.0

Build Application Navigation Bar Component

import React, { Component } from 'react';
import { Collapse, Nav, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';

export default class AppNavbar extends Component {
  constructor(props) {
    super(props);
    this.state = {isOpen: false};
    this.toggle = this.toggle.bind(this);
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
    return <Navbar color="dark" dark expand="md">
      <NavbarBrand tag={Link} to="/">Home</NavbarBrand>
      <NavbarToggler onClick={this.toggle}/>
      <Collapse isOpen={this.state.isOpen} navbar>
        <Nav className="ml-auto" navbar>
          <NavItem>
            <NavLink
              href="https://loizenjava.com">loizenjava.com</NavLink>
          </NavItem>
          <NavItem>
            <NavLink href="https://github.com/loizenjava">GitHub</NavLink>
          </NavItem>
        </Nav>
      </Collapse>
    </Navbar>;
  }
}

Create Reactjs Home Page Component

Project Goal Customer List
Project Goal Customer List

import React, { Component } from 'react';
import './App.css';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';
import { Button, Container } from 'reactstrap';

class Home extends Component {
  render() {
    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <Button color="link"><Link to="/customers">Manage Customer List</Link></Button>
        </Container>
      </div>
    );
  }
}

export default Home;

Build Reactjs CustomerList Component

Project Goal Customer List
Project Goal Customer List

– CustomerList Component will fetch a list of customers from Nodejs RestAPI api/customers and then shows all of them on a Bootstrap table.
– The CustomerList has 3 buttons:

  • Add Customer & Edit are used to link to a url /customers/new that will map with CustomerEdit component
  • Delete button is used to remove a Customer entity from PostgreSQL data based on a given id through an async function remove(id) that will do a fetch request with DELETE method to Nodejs RestAPI.

Detail coding:

import React, { Component } from 'react';
import { Button, ButtonGroup, Container, Table } from 'reactstrap';
import AppNavbar from './AppNavbar';
import { Link } from 'react-router-dom';

class CustomerList extends Component {

  constructor(props) {
    super(props);
    this.state = {customers: [], isLoading: true};
    this.remove = this.remove.bind(this);
  }

  componentDidMount() {
    this.setState({isLoading: true});

    fetch('api/customers')
      .then(response => response.json())
      .then(data => this.setState({customers: data, isLoading: false}));
  }

  async remove(id) {
    await fetch(`/api/customer/${id}`, {
      method: 'DELETE',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }).then(() => {
      let updatedCustomers = [...this.state.customers].filter(i => i.id !== id);
      this.setState({customers: updatedCustomers});
    });
  }

  render() {
    const {customers, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    const customerList = customers.map(customer => {
      return <tr key={customer.id}>
        <td style={{whiteSpace: 'nowrap'}}>{customer.firstname}</td>
        <td>{customer.lastname}</td>
        <td>{customer.age}</td>
        <td>{customer.address}</td>
        <td><a href={customer.copyright}>{customer.copyright}</a></td>
        <td>
          <ButtonGroup>
            <Button size="sm" color="primary" tag={Link} to={"/customers/" + customer.id}>Edit</Button>
            <Button size="sm" color="danger" onClick={() => this.remove(customer.id)}>Delete</Button>
          </ButtonGroup>
        </td>
      </tr>
    });

    return (
      <div>
        <AppNavbar/>
        <Container fluid>
          <div className="float-right">
            <Button color="success" tag={Link} to="/customers/new">Add Customer</Button>
          </div>
          <h3>Customer List</h3>
          <Table className="mt-4">
            <thead>
              <tr>
                <th width="20%">Firstname</th>
                <th width="20%">Lastname</th>
                <th width="10%">Age</th>
                <th>Address</th>
                <th>Copyrightby</th>
                <th width="10%">Actions</th>
              </tr>
            </thead>
            <tbody>
            {customerList}
            </tbody>
          </Table>
        </Container>
      </div>
    );
  }
}

export default CustomerList;

Build Reactjs CustomerEdit Component

Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database
Project Goal – Reactjs Update Customer through Nodejs RestAPI to MySQL database

We create a React Form to Put/Post data to PostgreSQL database through Nodejs RestAPI by using a fetch (PUT/POST) function:

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

After form submition, React Application will come back to a CustomerList component by using a coding-line:

this.props.history.push('/customers');

– Full coding:

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Button, Container, Form, FormGroup, Input, Label } from 'reactstrap';
import AppNavbar from './AppNavbar';

class CustomerEdit extends Component {

  emptyCustomer = {
    firstname: '',
    lastname: '',
    age: '',
    address: '',
    copyrigtby: ''
  };

  constructor(props) {
    super(props);
    this.state = {
      item: this.emptyCustomer
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  async componentDidMount() {
    if (this.props.match.params.id !== 'new') {
      const customer = await (await fetch(`/api/customer/${this.props.match.params.id}`)).json();
      this.setState({item: customer});
    }
  }

  handleChange(event) {
    const target = event.target;
    const value = target.value;
    const name = target.name;
    let item = {...this.state.item};
    item[name] = value;
    this.setState({item});
  }

  async handleSubmit(event) {
    event.preventDefault();
    const {item} = this.state;

    await fetch('/api/customer', {
      method: (item.id) ? 'PUT' : 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(item),
    });
    this.props.history.push('/customers');
  }

  render() {
    const {item} = this.state;
    const title = <h2>{item.id ? 'Edit Customer' : 'Add Customer'}</h2>;

    return <div>
      <AppNavbar/>
      <Container>
        {title}
        <Form onSubmit={this.handleSubmit}>
          <FormGroup>
            <Label for="firstname">Firstname</Label>
            <Input type="text" name="firstname" id="firstname" value={item.firstname || ''}
                   onChange={this.handleChange} autoComplete="firstname"/>
          </FormGroup>
          <FormGroup>
            <Label for="lastname">Lastname</Label>
            <Input type="text" name="lastname" id="lastname" value={item.lastname || ''}
                   onChange={this.handleChange} autoComplete="lastname"/>
          </FormGroup>          
          <FormGroup>
            <Label for="age">Age</Label>
            <Input type="text" name="age" id="age" value={item.age || ''}
                   onChange={this.handleChange} autoComplete="age"/>
          </FormGroup>
          <FormGroup>
            <Label for="address">Address</Label>
            <Input type="text" name="address" id="address" value={item.address || ''}
                   onChange={this.handleChange} autoComplete="address"/>
          </FormGroup>
          <FormGroup>
            <Button color="primary" type="submit">Save</Button>{' '}
            <Button color="secondary" tag={Link} to="/customers">Cancel</Button>
          </FormGroup>
        </Form>
      </Container>
    </div>
  }
}

export default withRouter(CustomerEdit);

Edit Reactjs App.js Component

App.js uses React Router to navigate between components.

  • path “/” is mapped with Home component
  • path “/customers” is mapped with CustomerList component
  • path “customers/:id” is mapped with CustomerEdit component
import React, { Component } from 'react';
import './App.css';
import Home from './Home';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import CustomerList from './CustomerList';
import CustomerEdit from './CustomerEdit';

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route path='/' exact={true} component={Home}/>
          <Route path='/customers' exact={true} component={CustomerList}/>
          <Route path='/customers/:id' component={CustomerEdit}/>
        </Switch>
      </Router>
    )
  }
}

export default App;

Add a Proxy Setting for calling RestAPIs

To proxy from /api to http://localhost:8080/api, add a proxy setting to app/package.json.

"scripts": {...},
"proxy": "http://localhost:8080",

Integrative Testing: Reactjs Application with Nodejs CRUD RestAPIs + PostgreSQL

– Run Nodejs project, check PostgreSQL database:

Check PostgreSQL customers table right after initing
Check PostgreSQL customers table right after initing

– Start Reactjs Application by cmd: yarn start.

Project Goal Home Page
Project Goal Home Page

Testcase 1: Reactjs Post request – Post data to PostgreSQL through Nodejs RestAPI

Project Goal - Reactjs Add a Customer through Nodejs RestAPI
Project Goal – Reactjs Add a Customer through Nodejs RestAPI

Testcase 2: Reactjs Put request – Put data to PostgreSQL through Nodejs RestAPI

Project Goal - Reactjs Update Customer through Nodejs RestAPI to MySQL database
Project Goal – Reactjs Update Customer through Nodejs RestAPI to MySQL database

Testcase 3: Reactjs Fetch request – Get All data from PostgreSQL through Nodejs RestAPI

Reactjs application show list data after update a customer
Reactjs application show list data after update a customer

Testcase 4: Reactjs Delete request – Delete an entity from PostgreSQL through Nodejs RestAPI

Delete a Customer with id=2, check the CustomerList after successfully:

Reactjs show list customers after doing CRUD operations
Reactjs show list customers after doing CRUD operations

– Check PostgreSQL database after doing all CRUD operations:

Check PostgreSQL database after doing CRUD operations
Check PostgreSQL database after doing CRUD operations

Further Reading

Related posts:


Sourcecode – Nodejs React.js CRUD Example (React.js + Nodejs + PostgreSQL)

– Full Sourcecode: React.js + Nodejs + PostgreSQL – Nodejs React.js CRUD Example

1. Reactjs

React.js-Nodejs-PostgreSQL-CRUD-Example

2. Nodejs RestAPI

Nodejs-Reactjs-PostgreSQL-Example

– Github Sourcecode:

1. Reactjs.

Reactjs – Github

2. Nodejs RestAPI:

Nodejs RestAPI – Github

Leave a Reply

Your email address will not be published. Required fields are marked *