Home > Article > Web Front-end > 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
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
This 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
Here we installed Express and body-parser and cors, used to handle HTTP requests and cross-domain requests.
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}`); });
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).
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
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
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
This will create a new folder named client
under the project folder to store our React front-end application code.
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>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
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!