React与Express搭建的图片上传器拖拽上传时出现404错误求助
Hey there! Let's break down why you're hitting that 404 error and get your drag-and-drop image uploader working properly. Here are the key issues and fixes:
1. Port Mismatch Causing the 404
Your React app is running on localhost:3000, but your Express server is listening on port 5000. When you call axios.post('/upload'), it's sending the request to http://localhost:3000/upload—which doesn't exist, hence the 404.
You have two easy fixes for this:
- Option 1: Use the full server URL in your axios call:
const res = await axios.post('http://localhost:5000/upload', formData, { ... }) - Option 2: Set up a proxy in your React project's
package.json(cleaner approach):
Add this line at the top level of yourpackage.json:
Now you can keep using"proxy": "http://localhost:5000"/uploadin your axios call, and React will automatically forward the request to your Express server.
2. Async useState Update Leading to Empty FormData
In your dropHandler, you're using setFile() to update state, then immediately creating a FormData with the file state. But useState updates are asynchronous—so at that point, file is still empty!
Instead, use the file you directly grab from the drop event, not the state variable. Here's how to fix the dropHandler:
const dropHandler = async (ev) => { ev.preventDefault(); let selectedFile = null; // Grab the first file from the drop event if (ev.dataTransfer.items) { for (let i = 0; i < ev.dataTransfer.items.length; i++) { if (ev.dataTransfer.items[i].kind === 'file') { selectedFile = ev.dataTransfer.items[i].getAsFile(); break; // Stop at the first file (adjust if you want multiple files) } } } else { // Fallback for older browsers selectedFile = ev.dataTransfer.files[0]; } if (!selectedFile) return; // Exit if no file was dropped setFile(selectedFile); // Update state for your UI if needed // Create FormData with the directly selected file const formData = new FormData(); formData.append('file', selectedFile); try { const res = await axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' }, }); const { fileName, filePath } = res.data; setUploadedFile({ fileName, filePath }); } catch (err) { if (err.response?.status === 500) { console.log('服务器出现问题'); } else { console.log(err.response?.data?.msg || '上传失败'); } } };
3. Ensure the Uploads Folder Exists
Your server tries to save files to client/public/uploads, but if that folder doesn't exist, you'll get a 500 error after fixing the 404. Let's add code to create the folder automatically if it's missing:
Update your server.js:
const express = require('express'); const fileUpload = require('express-fileupload'); const fs = require('fs'); const path = require('path'); const app = express(); app.use(fileUpload()); // Create uploads directory if it doesn't exist const uploadsDir = path.join(__dirname, 'client', 'public', 'uploads'); if (!fs.existsSync(uploadsDir)) { fs.mkdirSync(uploadsDir, { recursive: true }); // recursive creates parent folders too } // Upload endpoint app.post('/upload', (req, res) => { if (!req.files || !req.files.file) { return res.status(400).json({ msg: 'No file uploaded' }); } const file = req.files.file; const uploadPath = path.join(uploadsDir, file.name); file.mv(uploadPath, (err) => { if (err) { console.error(err); return res.status(500).json({ msg: '上传文件失败', error: err.message }); } res.json({ fileName: file.name, filePath: `/uploads/${file.name}` }); }); }); app.listen(5000, () => console.log('Server Started on port 5000...'));
Final Checks
- Restart both your React app and Express server after making these changes.
- Make sure your Express server is running on port 5000 (you should see the "Server Started on port 5000..." log).
- Drop a file into your upload zone—this should now work without the 404 error!
内容的提问来源于stack exchange,提问作者Ope Afolabi

