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

PHPz
Release: 2023-09-26 13:09:03
Original
1391 people have browsed it

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

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template