Skip to main content

Python print() Function

When you start learning Python, one of the first things you need to learn is how to display information on the screen. For example, you might want to display: A welcome message. Your name and age. The result of a mathematical calculation. Student marks and results. Information generated by a Python program. Python provides a built-in function called print() for displaying information. The print() function is one of the simplest and most frequently used functions in Python. It helps programmers display information while testing programs, solving problems, and developing applications. In this article, we will learn how to use print() with practical examples and their outputs. 1. What Is the print() Function in Python? The print() function is a built-in Python function that displays information in the output area, usually the terminal or console. Let's look at a simple example. print("Hello, World!") Output: Hello, World! In this example, Python displays the text Hello,...

Connecting React Frontend with Express Backend in the PERN Stack

Introduction

In the previous article, we learned the fundamentals of React.js including:

  • Components

  • JSX

  • Props

  • State

  • Event handling

Now it is time to connect the frontend with the backend and build a complete full-stack application.

This is one of the most exciting parts of the PERN stack because:

  • React frontend will communicate with Express APIs

  • Backend will fetch data from PostgreSQL

  • Data will appear dynamically on the webpage

In this article, we will learn:

  • How frontend and backend communicate

  • Using fetch()

  • Using Axios

  • React Hooks

  • Fetching API data

  • Displaying database records

  • Handling forms

  • Creating frontend CRUD operations


Understanding Full-Stack Communication

In the PERN stack:

React Frontend
       ↓
HTTP Request
       ↓
Express Backend
       ↓
PostgreSQL Database

Process Flow

  1. User clicks button in React

  2. React sends request to backend

  3. Express receives request

  4. PostgreSQL processes data

  5. Backend sends response

  6. React updates UI


What is an API Request?

When frontend communicates with backend, it sends:

  • GET requests

  • POST requests

  • PUT requests

  • DELETE requests

These are called API requests.


Example Backend API

Suppose backend route is:

app.get('/students', async (req, res) => {

    const students = await pool.query(
        'SELECT * FROM students'
    );

    res.json(students.rows);
});

This API returns student data in JSON format.


What is JSON?

JSON stands for:

JavaScript Object Notation

It is used for data exchange between frontend and backend.

Example:

[
    {
        "student_id": 1,
        "name": "Rahul",
        "course": "BCA",
        "age": 20
    }
]

Fetching Data Using fetch()

JavaScript provides:

fetch()

to communicate with APIs.


Basic Fetch Example

fetch('http://localhost:5000/students')
    .then(response => response.json())
    .then(data => console.log(data));

Understanding the Code

PartPurpose
fetch()Sends request
response.json()Converts JSON
dataAPI response

Using useEffect Hook

React provides:

useEffect()

for running code when component loads.


Why useEffect is Important

Without useEffect(), API calls may run repeatedly.

It helps:

  • Load data once

  • Improve performance

  • Avoid unnecessary API calls


Example of useEffect

import { useEffect } from 'react';

useEffect(() => {

    console.log('Component Loaded');

}, []);

Understanding Empty Dependency Array

[]

means:

  • Run only once

  • When component loads


Fetching API Data in React

Now let’s fetch student data properly.


Complete Example

import { useState, useEffect } from 'react';

function App() {

    const [students, setStudents] = useState([]);

    useEffect(() => {

        getStudents();

    }, []);

    const getStudents = async () => {

        const response = await fetch(
            'http://localhost:5000/students'
        );

        const data = await response.json();

        setStudents(data);
    };

    return (
        <div>

            <h1>Student List</h1>

            {students.map(student => (

                <div key={student.student_id}>

                    <h3>{student.name}</h3>

                    <p>{student.course}</p>

                </div>

            ))}

        </div>
    );
}

export default App;

Understanding map()

students.map()

loops through array data and displays elements dynamically.


Why key is Required

React requires:

key

to identify unique elements efficiently.

Example:

key={student.student_id}

What is Axios?

is a popular library used for API requests.

Many developers prefer Axios because:

  • Simpler syntax

  • Better error handling

  • Faster development


Installing Axios

Run:

npm install axios

Axios GET Request Example

import axios from 'axios';

const response = await axios.get(
    'http://localhost:5000/students'
);

console.log(response.data);

fetch() vs Axios

fetch()Axios
Built into browserExternal package
More codeCleaner syntax
Manual JSON conversionAutomatic conversion

Creating a Form in React

Now let’s create a form to insert student data.


Example Form

import { useState } from 'react';

function AddStudent() {

    const [name, setName] = useState('');

    return (
        <div>

            <input
                type="text"
                placeholder="Enter Name"
                value={name}
                onChange={(e) => setName(e.target.value)}
            />

        </div>
    );
}

export default AddStudent;

Controlled Components

React forms are called:

Controlled Components

because React controls form values using state.


Handling Form Submission

const handleSubmit = async (e) => {

    e.preventDefault();

    console.log('Form Submitted');
};

Why preventDefault() is Used

e.preventDefault()

prevents page refresh during form submission.


Sending POST Request

const body = { name, course, age };

await fetch(
    'http://localhost:5000/students',
    {
        method: 'POST',

        headers: {
            'Content-Type': 'application/json'
        },

        body: JSON.stringify(body)
    }
);

Understanding JSON.stringify()

JSON.stringify()

converts JavaScript object into JSON string.


Updating Data in React

PUT request example:

await fetch(
    `http://localhost:5000/students/${id}`,
    {
        method: 'PUT',

        headers: {
            'Content-Type': 'application/json'
        },

        body: JSON.stringify(updatedStudent)
    }
);

Deleting Data in React

DELETE request example:

await fetch(
    `http://localhost:5000/students/${id}`,
    {
        method: 'DELETE'
    }
);

Full CRUD Flow

OperationFrontend Action
CreateForm submission
ReadFetch data
UpdateEdit form
DeleteDelete button

Handling Errors in React

Always use:

try...catch

Example:

try {

    const response = await fetch(url);

} catch (err) {

    console.error(err.message);
}

CORS Error in React

Sometimes frontend cannot connect to backend.

This happens because of:

CORS Policy

Fixing CORS Error

Install CORS package in backend:

npm install cors

Inside backend:

const cors = require('cors');

app.use(cors());

Real-World Use Cases

React frontend + Express backend is used in:

  • Student portals

  • Online test systems

  • E-commerce platforms

  • Banking dashboards

  • SaaS applications


Best Practices

Keep API URLs Separate

Use:

.env

files for API URLs.


Create Reusable Components

Separate:

  • Forms

  • Tables

  • Buttons

  • Cards


Validate Forms Properly

Check:

  • Empty inputs

  • Invalid email

  • Password length


Use Loading States

Show loading message while fetching data.

Example:

Loading...

Common Beginner Mistakes

Forgetting await

Wrong:

const response = fetch(url);

Correct:

const response = await fetch(url);

Not Converting JSON

Wrong:

const data = response;

Correct:

const data = await response.json();

Infinite API Calls

Wrong:

useEffect(() => {

    getStudents();

});

Correct:

useEffect(() => {

    getStudents();

}, []);

Conclusion

You have now learned how to connect React frontend with Express backend in the PERN stack.

You learned:

  • API requests

  • fetch()

  • Axios

  • useEffect()

  • Form handling

  • CRUD operations

  • Error handling

  • Dynamic UI rendering

Now your application is becoming a real full-stack web application.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...