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

相关推荐
码事漫谈3 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
许杰小刀3 小时前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
我是Superman丶4 小时前
Element UI 表格某行突出悬浮效果
前端·javascript·vue.js
恋猫de小郭4 小时前
你的代理归我了:AI 大模型恶意中间人攻击,钱包都被转走了
前端·人工智能·ai编程
xiaokuangren_4 小时前
前端css颜色
前端·css
hoiii1875 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
anOnion5 小时前
构建无障碍组件之Meter Pattern
前端·html·交互设计
小码哥_常5 小时前
Spring Boot配置diff:解锁配置管理新姿势
前端
小码哥_常5 小时前
告别onActivityResult!Android数据回传的3大痛点与终极解决方案
前端
hhcccchh5 小时前
1.2 CSS 基础选择器、盒模型、flex 布局、grid 布局
前端·css·css3