React, Node.js, MySQL CRUD App: A Simple Tutorial

by Alex Braham 50 views

Hey guys! Let's dive into building a full-stack web application using React for the frontend, Node.js with Express for the backend, and MySQL for the database. We'll create a simple CRUD (Create, Read, Update, Delete) application. This is a fundamental project that will give you a solid understanding of how these technologies work together. So, buckle up and let's get started!

Setting Up the Development Environment

Before we begin coding, we need to set up our development environment. This involves installing Node.js, MySQL, and setting up our project directories. This initial setup is crucial for a smooth development process, so let's walk through it step by step.

Installing Node.js and npm

First, you'll need Node.js installed on your machine. Node.js is a JavaScript runtime that allows you to run JavaScript code outside of a web browser. It also comes with npm (Node Package Manager), which we'll use to install various packages and libraries.

Go to the official Node.js website (https://nodejs.org/) and download the LTS (Long Term Support) version. The LTS version is recommended for most users as it's more stable.

Once the download is complete, run the installer and follow the instructions. After installation, open your terminal or command prompt and verify that Node.js and npm are installed correctly by running the following commands:

node -v
npm -v

These commands should display the versions of Node.js and npm installed on your system. If you see the version numbers, you're good to go!

Installing MySQL

Next, we'll install MySQL, which will serve as our database. MySQL is a popular open-source relational database management system.

You can download MySQL from the official MySQL website (https://www.mysql.com/). Choose the appropriate version for your operating system and follow the installation instructions.

During the installation, you'll be prompted to set a root password. Make sure to remember this password, as you'll need it to access and manage your MySQL database.

After installation, you might want to install MySQL Workbench, a GUI tool for managing MySQL databases. It's optional, but it can make working with MySQL much easier.

Setting Up Project Directories

Now that we have Node.js and MySQL installed, let's set up our project directories. Create a main project folder, and inside it, create two subfolders: frontend and backend. This structure will help us keep our frontend and backend code separate and organized.

your-project-name/
├── frontend/
└── backend/

In the backend folder, we'll initialize a Node.js project using npm. Open your terminal, navigate to the backend folder, and run the following command:

npm init -y

This command creates a package.json file, which will store information about our project, including its dependencies.

In the frontend folder, we'll set up a React application using Create React App. Open your terminal, navigate to the frontend folder, and run the following command:

npx create-react-app .

This command creates a new React application in the current directory. It might take a few minutes to complete.

Once Create React App is finished, you'll have a basic React application ready to go. Now that our development environment is set up, we can start building our CRUD application.

Building the Backend with Node.js and Express

The backend is the heart of our application, handling data storage and retrieval. We'll use Node.js with Express to create our API endpoints. This involves setting up an Express server, connecting to our MySQL database, and defining the CRUD operations.

Installing Dependencies

First, let's install the necessary dependencies for our backend. Navigate to the backend folder in your terminal and run the following command:

npm install express mysql cors body-parser

Here's what each of these packages does:

  • express: A web application framework for Node.js.
  • mysql: A Node.js driver for connecting to MySQL databases.
  • cors: Middleware for enabling Cross-Origin Resource Sharing (CORS).
  • body-parser: Middleware for parsing request bodies.

Creating the Express Server

Create a file named server.js in the backend folder. This file will contain our Express server code.

const express = require('express');
const mysql = require('mysql');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const port = 3001;

app.use(cors());
app.use(bodyParser.json());

const db = mysql.createConnection({
  host: 'localhost',
  user: 'your_mysql_username',
  password: 'your_mysql_password',
  database: 'your_database_name',
});

db.connect((err) => {
  if (err) {
    console.error('MySQL connection error:', err);
  } else {
    console.log('Connected to MySQL database');
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Replace your_mysql_username, your_mysql_password, and your_database_name with your actual MySQL credentials and database name.

Defining API Endpoints (CRUD Operations)

Now, let's define the API endpoints for our CRUD operations. We'll create endpoints for creating, reading, updating, and deleting data.

Create (POST)

app.post('/api/create', (req, res) => {
  const { name, age, country } = req.body;
  const sql = 'INSERT INTO users (name, age, country) VALUES (?, ?, ?)';
  db.query(sql, [name, age, country], (err, result) => {
    if (err) {
      console.error('Error creating user:', err);
      res.status(500).json({ error: 'Failed to create user' });
    } else {
      console.log('User created successfully');
      res.status(200).json({ message: 'User created successfully' });
    }
  });
});

Read (GET)

app.get('/api/users', (req, res) => {
  const sql = 'SELECT * FROM users';
  db.query(sql, (err, result) => {
    if (err) {
      console.error('Error fetching users:', err);
      res.status(500).json({ error: 'Failed to fetch users' });
    } else {
      res.status(200).json(result);
    }
  });
});

Update (PUT)

app.put('/api/update/:id', (req, res) => {
  const { id } = req.params;
  const { name, age, country } = req.body;
  const sql = 'UPDATE users SET name = ?, age = ?, country = ? WHERE id = ?';
  db.query(sql, [name, age, country, id], (err, result) => {
    if (err) {
      console.error('Error updating user:', err);
      res.status(500).json({ error: 'Failed to update user' });
    } else {
      console.log('User updated successfully');
      res.status(200).json({ message: 'User updated successfully' });
    }
  });
});

Delete (DELETE)

app.delete('/api/delete/:id', (req, res) => {
  const { id } = req.params;
  const sql = 'DELETE FROM users WHERE id = ?';
  db.query(sql, [id], (err, result) => {
    if (err) {
      console.error('Error deleting user:', err);
      res.status(500).json({ error: 'Failed to delete user' });
    } else {
      console.log('User deleted successfully');
      res.status(200).json({ message: 'User deleted successfully' });
    }
  });
});

Running the Backend

To run the backend server, navigate to the backend folder in your terminal and run the following command:

node server.js

You should see the message "Server is running on port 3001" in your console.

Building the Frontend with React

Now that our backend is up and running, let's build the frontend using React. We'll create components to display data, handle user input, and communicate with our backend API. This involves fetching data from the API, displaying it in a user-friendly format, and allowing users to create, update, and delete data.

Installing Dependencies

We'll use axios to make HTTP requests to our backend API. Navigate to the frontend folder in your terminal and run the following command:

npm install axios

Creating Components

Let's create a few components to manage our data. We'll start with a UserList component to display the list of users and a UserForm component to handle user input.

UserList Component

Create a file named UserList.js in the src folder of your React application.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function UserList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await axios.get('http://localhost:3001/api/users');
      setUsers(response.data);
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  };

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.name} ({user.age}) - {user.country}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

UserForm Component

Create a file named UserForm.js in the src folder of your React application.

import React, { useState } from 'react';
import axios from 'axios';

function UserForm() {
  const [name, setName] = useState('');
  const [age, setAge] = useState('');
  const [country, setCountry] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post('http://localhost:3001/api/create', {
        name: name,
        age: age,
        country: country,
      });
      // Refresh the user list after creating a user
      window.location.reload();
    } catch (error) {
      console.error('Error creating user:', error);
    }
  };

  return (
    <div>
      <h2>Create User</h2>
      <form onSubmit={handleSubmit}>
        <label>Name:</label>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} /><br />
        <label>Age:</label>
        <input type="number" value={age} onChange={(e) => setAge(e.target.value)} /><br />
        <label>Country:</label>
        <input type="text" value={country} onChange={(e) => setCountry(e.target.value)} /><br />
        <button type="submit">Create</button>
      </form>
    </div>
  );
}

export default UserForm;

Integrating Components in App.js

Now, let's integrate these components into our App.js file.

import React from 'react';
import UserList from './UserList';
import UserForm from './UserForm';

function App() {
  return (
    <div className="App">
      <h1>React Node.js MySQL CRUD Example</h1>
      <UserForm />
      <UserList />
    </div>
  );
}

export default App;

Running the Frontend

To run the frontend application, navigate to the frontend folder in your terminal and run the following command:

npm start

This will start the React development server and open your application in your default web browser.

Conclusion

Alright, guys! You've successfully built a full-stack CRUD application using React, Node.js, and MySQL. You've learned how to set up your development environment, create a backend API with Node.js and Express, connect to a MySQL database, and build a frontend with React to interact with your API. This is a great foundation for building more complex web applications. Keep practicing and experimenting, and you'll become a full-stack ninja in no time!