在React前端和Node.js后端之间建立连接,通常是通过API接口进行的。以下是一个简单的例子,展示了如何在React前端使用fetch发送请求到Node.js后端的一个API接口,并处理响应。
Node.js后端 (server.js):
const express = require('express');
const app = express();
const port = 5000;
 
app.get('/api/data', (req, res) => {
  const responseData = { message: 'Hello from the server!' };
  res.json(responseData); // 返回JSON响应
});
 
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});确保启动Node.js服务器:
node server.jsReact前端 (App.js):
import React, { useState, useEffect } from 'react';
 
function App() {
  const [data, setData] = useState(null);
 
  useEffect(() => {
    fetch('http://localhost:5000/api/data')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => console.error('Error fetching data: ', error));
  }, []);
 
  if (!data) {
    return <div>Loading...</div>;
  }
 
  return (
    <div>
      <h1>Data from Server:</h1>
      <p>{data.message}</p>
    </div>
  );
}
 
export default App;在这个例子中,React组件使用useEffect钩子在组件挂载后发送GET请求到Node.js服务器的/api/data接口。服务器响应后,使用useState钩子更新组件的状态,并在组件中渲染数据。