使用 React 和 Node.js 创建一个简单的全栈应用程序
在我之前的博客中,我介绍了 React 和 Node.js。现在,让我们将它们结合起来,构建一个更令人兴奋的东西:一个简单的全栈应用程序!您可能认为全栈应用程序仅适用于具有多个数据库和复杂结构的大型项目。虽然从概念上讲这是正确的,但实际上,全栈应用程序可以像一个带有基本后端的小型前端一样简单。所以,让我们分解一下,看看使用 React 和 Node.js 创建全栈应用程序有多么容易。
步骤 1:使用 Node.js 和 Express 进行后端
让我们从创建后端开始。我们将使用 **Express** 作为服务器,向前端发送简单的 JSON 消息响应。
npm install express
const express = require('express'); const app = express(); const PORT = 3000; app.get('/greet', (req, res) => { res.status(200).json({ message: "Zee here..." }); }); app.listen(PORT, () => console.log(`Server is running at http://localhost:${PORT}`));
**解释**:
第 2 步:使用 React 进行前端
现在,让我们使用 **React** 创建前端。我们将使用两个钩子:`useState` 和 `useEffect` 从后端获取数据。
npx create-react-app my-fullstack-app cd my-fullstack-app
import { useState, useEffect } from 'react'; export function App() { const [response, setResponse] = useState(null); useEffect(() => { const controller = new AbortController(); // This is used to abort the fetch request if the component is unmounted const fetchData = async () => { try { const response = await fetch('http://localhost:3000/greet', { signal: controller.signal, }); if (!response.ok) throw new Error("Couldn't fetch data"); const data = await response.json(); setResponse(data.message); // Corrected the response property here } catch (error) { console.error(error); } }; fetchData(); // Clean up function to abort the fetch request if needed return () => controller.abort(); }, []); return ({response ?); }{response}
:Loading...
}
**解释**:
步骤 3:运行应用程序
node server.js
npm start
现在,打开浏览器并转到 `http://localhost:3000`。您应该看到从后端获取的一条简单消息,它将显示 `"Zee here..."`。
结论
就这样!您刚刚使用 React 和 Express 创建了一个简单的全栈应用程序。这是一个很好的开始,有了这个基础,您可以扩展和构建更复杂的应用程序。祝您编码愉快!