node后端react前端简单实例
安装node
mkdir my-node-server
cd my-node-server
npm init -y
npm install express cors
创建 server.js文件
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 4000;
app.use(cors()); // 允许跨域请求
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from Node.js server!' });
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
node server.js
访问地址:
http://localhost:5000/api/data
创建react
npx create-react-app my-react-app
cd my-react-app
src下创建App.js
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('http://localhost:4000/api/data') // 发送网络请求
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<h1>React Demo Application</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default App;
npm start
http://localhost:3000