


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:
-
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 - Create the project folder: in your working directory Create a new folder to store our full-stack application code.
2. Back-end construction
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 loginThis will create a default
package.json
file to record project-related information and dependent packages.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 loginHere we installed Express and body-parser and cors, used to handle HTTP requests and cross-domain requests.
- Create an Express server: Create a new JavaScript file in the root directory of the project folder and name it
server.js
. Openserver.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}`); });
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).
- 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); });
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.
Start the server: Execute the following command in the command line to start the Express server:
node server.js
Copy after loginIf 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
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 loginThis will create a new folder named
client
under the project folder to store our React front-end application code.- 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;
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.
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 loginIf 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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 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 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 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 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

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 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
