在Ubuntu环境下实现前后端分离,通常涉及以下几个步骤:
安装Node.js和npm:
sudo apt update
sudo apt install nodejs npm
node -v
npm -v
创建前端项目:
create-react-app(或其他前端框架如Vue.js、Angular等)创建前端项目。create-react-app:npm install -g create-react-app
npx create-react-app frontend
cd frontend
npm start
创建后端项目:
mkdir backend
cd backend
npm init -y
npm install 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
配置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}`);
});
前端请求后端API:
fetch或axios等库向后端发送请求。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请求进行通信。