Table of Contents
Todo List
Home Web Front-end JS Tutorial How to build a full-stack JavaScript application using React and Express

How to build a full-stack JavaScript application using React and Express

Sep 26, 2023 pm 01:09 PM
react express Full stack application

How to build a full-stack JavaScript application using React and Express

How to use React and Express to build a full-stack JavaScript application

Introduction:
React and Express are currently very popular JavaScript frameworks, which are used to build front-ends respectively and backend applications. This article will introduce how to use React and Express to build a full-stack JavaScript application. We will explain step by step how to build a simple TodoList application and provide specific code examples.

1. Preparation
Before we start, we need to prepare some necessary tools and environment:

  1. Node.js and npm: Make sure Node is installed .js and npm (the package manager for Node.js), you can check whether they have been installed successfully through the command line, as follows:

    node -v
    npm -v
    Copy after login
  2. Create the project folder: in your working directory Create a new folder to store our full-stack application code.

2. Back-end construction

  1. Initialize the project: Open the command line in the project folder and execute the following command to initialize a new Node.js project :

    npm init -y
    Copy after login

    This will create a default package.json file to record project-related information and dependent packages.

  2. Install Express and other dependencies: Execute the following commands in the command line to install Express and other required dependencies:

    npm install express body-parser cors --save
    Copy after login

    Here we installed Express and body-parser and cors, used to handle HTTP requests and cross-domain requests.

  3. Create an Express server: Create a new JavaScript file in the root directory of the project folder and name it server.js. Open server.js and add the following content:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

const PORT = process.env.PORT || 5000;

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

This code first introduces the required dependency packages, then creates an Express instance and sets up some middleware. Finally, we listen on the specified port (default is 5000).

  1. Add routing and API: Continue to edit server.js, add the following content below the existing code:
let todos = [];

app.get('/api/todos', (req, res) => {
  res.json(todos);
});

app.post('/api/todos', (req, res) => {
  const { todo } = req.body;
  todos.push(todo);
  res.json(todos);
});
Copy after login

This code definition There are two routes: one for getting all todo items, and one for adding new todo items. We use a simple array todos to store all todo items.

  1. Start the server: Execute the following command in the command line to start the Express server:

    node server.js
    Copy after login

    If everything is OK, you will see in the command line Server is running on port XXXX prompt indicates that the server has been started successfully.

3. Front-end construction

  1. Create a React application: Return to the project folder and execute the following command on the command line to create a new React application:

    npx create-react-app client
    Copy after login

    This will create a new folder named client under the project folder to store our React front-end application code.

  2. Edit React component: Open the client/src/App.js file you just created and replace the code in it with the following content:
import React, { useState, useEffect } from "react";

function App() {
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState("");

  useEffect(() => {
    fetch("/api/todos")
      .then(res => res.json())
      .then(data => setTodos(data));
  }, []);

  const handleInputChange = e => {
    setNewTodo(e.target.value);
  };

  const handleSubmit = e => {
    e.preventDefault();
    const todo = { todo: newTodo };

    fetch("/api/todos", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(todo)
    })
      .then(res => res.json())
      .then(data => setTodos(data))
      .catch(err => console.log(err));

    setNewTodo("");
  };

  return (
    <div>
      <h1 id="Todo-List">Todo List</h1>
      <form onSubmit={handleSubmit}>
        <input value={newTodo} onChange={handleInputChange} />
        <button type="submit">Add Todo</button>
      </form>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Copy after login

This code defines a React function componentApp, which is used to display the todo list. The component uses two React Hooks, useState and useEffect, to handle the state and side effects of the component. We use the fetch function to send HTTP requests and obtain data.

  1. Start the React application: Open the command line under the project folder, enter the client folder, and execute the following command to start the React development server:

    npm start
    Copy after login

    If everything goes well, you will see a simple TodoList application in the browser, and you can add new todo items.

Conclusion:
Through the steps in this article, we successfully built a simple full-stack JavaScript application using React and Express together. You can further extend the functionality of the application according to your needs, such as adding editing and deletion functions, or using a database to store data. Full-stack development allows us to give full play to the advantages of front-end and back-end technologies at the same time and improve development efficiency. I hope this article will be helpful to you.

The above is the detailed content of How to build a full-stack JavaScript application using React and Express. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React responsive design guide: How to achieve adaptive front-end layout effects React responsive design guide: How to achieve adaptive front-end layout effects Sep 26, 2023 am 11:34 AM

React Responsive Design Guide: How to Achieve Adaptive Front-end Layout Effects With the popularity of mobile devices and the increasing user demand for multi-screen experiences, responsive design has become one of the important considerations in modern front-end development. React, as one of the most popular front-end frameworks at present, provides a wealth of tools and components to help developers achieve adaptive layout effects. This article will share some guidelines and tips on implementing responsive design using React, and provide specific code examples for reference. Fle using React

React code debugging guide: How to quickly locate and solve front-end bugs React code debugging guide: How to quickly locate and solve front-end bugs Sep 26, 2023 pm 02:25 PM

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

See all articles