React如何将服务端的变量/值传递到客户端?
Got it, let's work through this together to get those filenames from your uploads directory over to your React client. The core issue here is probably handling asynchronous file reading correctly on the server, then setting up a proper API endpoint for your React app to fetch from.
Step 1: Fix the Server Side (server.js)
First, let's turn that test function into a working API endpoint that returns the list of filenames. Since reading files from the filesystem is asynchronous, we need to handle that properly with promises or async/await.
Here's how to update your server code:
const express = require('express'); const formidable = require('formidable'); const fs = require('fs').promises; // Use promise-based fs for cleaner async code const path = require('path'); const cors = require('cors'); // Add this if your React app runs on a different port const app = express(); app.use(cors()); // Enable CORS to allow cross-origin requests from React // Define the endpoint to get filenames app.get('/api/uploads/filenames', async (req, res) => { try { const uploadsDir = path.join(__dirname, 'uploads'); // Read all items in the uploads directory const files = await fs.readdir(uploadsDir); // Optional: Filter out directories if you only want files const fileNames = await Promise.all( files.map(async (file) => { const stats = await fs.stat(path.join(uploadsDir, file)); return stats.isFile() ? file : null; }) ).then(results => results.filter(Boolean)); // Remove null entries (directories) res.status(200).json({ filenames: fileNames }); } catch (error) { console.error('Error reading uploads directory:', error); res.status(500).json({ error: 'Failed to retrieve filenames' }); } }); // Keep your existing file upload logic with formidable here // ... (your existing upload endpoint code) const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Key fixes here:
- Using
fs.promisesfor async/await instead of callbacks, which makes error handling easier - Creating a dedicated GET endpoint
/api/uploads/filenamesthat returns the filenames as JSON - Adding CORS support (install it first with
npm install corsif you haven't) to avoid cross-origin errors when React fetches from the server - Filtering out directories if you only want actual files (optional but useful)
Step 2: Fetch Data in Your React Component (Dropuploadfile.js)
Now, in your React component, you'll use fetch (or Axios if you prefer) to call the new API endpoint, store the filenames in state, and render them.
Here's an example implementation:
import React, { useState, useEffect } from 'react'; const Dropuploadfile = () => { const [filenames, setFilenames] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchFilenames = async () => { try { const response = await fetch('http://localhost:5000/api/uploads/filenames'); if (!response.ok) { throw new Error('Failed to fetch filenames'); } const data = await response.json(); setFilenames(data.filenames); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchFilenames(); }, []); // Empty dependency array runs this once on component mount return ( <div> <h2>Uploaded Files</h2> {loading && <p>Loading filenames...</p>} {error && <p className="error">Error: {error}</p>} {!loading && !error && ( <ul> {filenames.length === 0 ? ( <li>No files uploaded yet</li> ) : ( filenames.map((name, index) => ( <li key={index}>{name}</li> )) )} </ul> )} {/* Keep your existing drop/upload UI here */} {/* ... */} </div> ); }; export default Dropuploadfile;
What this does:
- Uses React's
useStateto track filenames, loading state, and errors useEffectruns the fetch function once when the component mounts- Handles loading and error states to give feedback to the user
- Renders the list of filenames once they're fetched
Quick Notes
- Make sure your
uploadsdirectory exists on the server (you can add code to create it if it doesn't, usingfs.mkdir(uploadsDir, { recursive: true })) - If you're using Axios instead of
fetch, the logic is similar—just replace the fetch call withaxios.get() - Double-check the server URL in your React fetch call (match the port your Express server is running on)
内容的提问来源于stack exchange,提问作者Zhen Hao Tan

