


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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:

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 Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

How to use React to develop a responsive backend management system. With the rapid development of the Internet, more and more companies and organizations need an efficient, flexible, and easy-to-manage backend management system to handle daily operations. As one of the most popular JavaScript libraries currently, React provides a concise, efficient and maintainable way to build user interfaces. This article will introduce how to use React to develop a responsive backend management system and give specific code examples. Create a React project first
