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

相关推荐
爱上好庆祝1 小时前
学习js的第五天
前端·css·学习·html·css3·js
C澒1 小时前
IntelliPro 产研协作平台:基于 AI Agent 的低代码智能化配置方案设计与实现
前端·低代码·ai编程
一袋米扛几楼981 小时前
【Git】规范化协作:详解 GitHub 工作流中的 Issue、Branch 与 Pull Request 最佳实践
前端·git·github·issue
网络点点滴1 小时前
前端与后端的区别与联系
前端
EnCi Zheng2 小时前
M5-markconv自定义CSS样式指南 [特殊字符]
前端·css·python
kyriewen2 小时前
你的网页慢,用户不说直接走——前端性能监控教你“读心术”
前端·性能优化·监控
广州华水科技2 小时前
北斗GNSS变形监测在大坝安全监测中的应用与优势分析
前端
前端老石人2 小时前
前端开发中的 URL 完全指南
开发语言·前端·javascript·css·html
CAE虚拟与现实2 小时前
五一假期闲来无事,来个前段、后端的说明吧
前端·后端·vtk·three.js·前后端
Sarvartha2 小时前
三目运算符
linux·服务器·前端