Home >Web Front-end >JS Tutorial >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

WBOY
WBOYOriginal
2023-09-28 10:48:291704browse

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end

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 of all, 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 together. All HTML, CSS and JavaScript codes are generated by the back-end, and the front-end and back-end codes are mixed together. Front-end and back-end separation separates the front-end and back-end code so that the front-end and back-end can be developed and deployed independently.

React is a very popular front-end framework. It provides a component-based development model, making front-end development more modular and easier to maintain. We will use React as the front-end framework to achieve front-end and back-end separation.

The following is a specific code example that demonstrates how to use React Node.js to achieve front-end and back-end separation.

First, we need to create a React project. You can use the create-react-app tool to create a new React project:

npx create-react-app frontend

Next, we create a simple React component to display the data returned by the backend. Create a new file HelloWorld.js in the src folder and add the following code:

import React from 'react';

class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: '',
    };
  }

  componentDidMount() {
    fetch('/api/helloworld')
      .then(response => response.json())
      .then(data => this.setState({ message: data.message }));
  }

  render() {
    return (
      <div>
        <h1>Hello World!</h1>
        <p>{this.state.message}</p>
      </div>
    );
  }
}

export default HelloWorld;

This component uses the fetch API to obtain data from the backend and display the data on the page.

Next, we need to create a backend server. A simple backend server can be created using Node.js and the Express framework. Create a new file server.js in the project root directory and add the following code:

const express = require('express');
const app = express();

app.get('/api/helloworld', (req, res) => {
  res.send({ message: 'Hello World from the backend!' });
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

This server will listen to port 5000 and provide an API interface of /api/helloworld, returning an API containing "Hello World from the backend!" JSON object.

Finally, we need to connect the front-end and back-end projects. Create a new file setupProxy.js in the root directory of the React project and add the following code:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

This file is used to forward the front-end API request to the back-end address.

Now, we can run the front-end and back-end projects. In the terminal, enter the root directory of the React project and the directory where server.js is located, and then run the following commands:

# React项目
npm start

# 后端服务器
node server.js

By accessing http://localhost:3000, we can see a file containing " Hello World from the backend!" page.

Through the above examples, we have successfully achieved the separation of React's front-end and back-end, and the front-end and back-end can be developed and deployed independently. By decoupling front-end and back-end code, we can better organize the project structure and improve development efficiency. At the same time, independent deployment also allows us to be more flexible in project launch and maintenance.

In actual development, the appropriate technology stack and framework can be selected according to specific needs and architecture to achieve front-end and back-end separation. React is just one of the options. I believe that through the above examples, you can already master the basic ideas and methods.

To sum up, the separation of React front-end and back-end requires the following steps: creating a React project, implementing front-end components, creating a back-end server, and connecting front-end and front-end projects. Through these steps, we can achieve decoupling and independent deployment of the front and back ends.

I hope this article will be helpful to you, and I wish you success in the development of front-end and back-end separation!

The above is the detailed content of Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end. For more information, please follow other related articles on the PHP Chinese website!

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