温馨提示×

ubuntu js如何实现前后端分离

小樊
33
2025-11-11 02:33:47
栏目: 编程语言

在Ubuntu环境下实现前后端分离,通常涉及以下几个步骤:

  1. 安装Node.js和npm

    • 打开终端。
    • 使用以下命令安装Node.js和npm(Node包管理器):
      sudo apt update
      sudo apt install nodejs npm
      
    • 验证安装:
      node -v
      npm -v
      
  2. 创建前端项目

    • 使用create-react-app(或其他前端框架如Vue.js、Angular等)创建前端项目。
    • 安装create-react-app
      npm install -g create-react-app
      
    • 创建一个新的React应用:
      npx create-react-app frontend
      
    • 进入前端项目目录并启动开发服务器:
      cd frontend
      npm start
      
  3. 创建后端项目

    • 使用Express.js(或其他后端框架如Koa.js、Django等)创建后端项目。
    • 在终端中创建一个新的Node.js项目:
      mkdir backend
      cd backend
      npm init -y
      
    • 安装Express.js:
      npm install express
      
    • 创建一个简单的Express服务器:
      // backend/index.js
      const express = require('express');
      const app = express();
      const port = 5000;
      
      app.get('/', (req, res) => {
        res.send('Hello World!');
      });
      
      app.listen(port, () => {
        console.log(`Server running on http://localhost:${port}`);
      });
      
    • 启动后端服务器:
      node index.js
      
  4. 配置CORS(跨域资源共享)

    • 由于前后端分离,前端和后端通常运行在不同的端口上,因此需要配置CORS。
    • 在Express服务器中添加CORS中间件:
      // backend/index.js
      const express = require('express');
      const cors = require('cors');
      const app = express();
      const port = 5000;
      
      app.use(cors());
      
      app.get('/', (req, res) => {
        res.send('Hello World!');
      });
      
      app.listen(port, () => {
        console.log(`Server running on http://localhost:${port}`);
      });
      
  5. 前端请求后端API

    • 在前端项目中,使用fetchaxios等库向后端发送请求。
    • 例如,使用fetch在React组件中请求后端数据:
      // frontend/src/App.js
      import React, { useEffect, useState } from 'react';
      
      function App() {
        const [message, setMessage] = useState('');
      
        useEffect(() => {
          fetch('http://localhost:5000/')
            .then(response => response.text())
            .then(data => setMessage(data));
        }, []);
      
        return (
          <div className="App">
            <header className="App-header">
              <p>{message}</p>
            </header>
          </div>
        );
      }
      
      export default App;
      

通过以上步骤,你可以在Ubuntu环境下实现前后端分离。前端和后端分别运行在不同的进程中,通过HTTP请求进行通信。

0