修复生产环境React路由后,Fetch无法找到API URL的问题求助
Hey there, let's sort out this problem you're facing! The issue here boils down to Express route matching order—your catch-all React route is swallowing all your API requests before they can reach the intended endpoints.
Why This Happens
When you added app.get('/*', ...) to fix React's client-side routing, this route acts as a wildcard that matches every GET request (including those starting with /api). Since Express processes routes in the order they're defined, your API endpoints never get hit because the catch-all route grabs the request first and sends back React's index.html instead.
The Fix: Reorder Your Routes
You just need to define your API routes before the catch-all React route. This way, Express will check for matches against your API endpoints first, and only fall back to serving React's index.html for any routes that aren't API-related.
Here's how your corrected server.js should look:
const express = require('express'); const path = require('path'); const app = express(); // 1. First, define all your API routes app.get('/api/customers', (req, res) => { const customers = [ {id: 2, firstName: 'Test', lastName: 'Case'}, {id: 3, firstName: 'Foo', lastName: 'Bar'} ]; res.json(customers); // Don't forget to send the JSON response! }); // 2. Serve React's static build files app.use(express.static(path.join(__dirname, 'client', 'build'))); // 3. Finally, the catch-all route for React client-side routing app.get('/*', function (req, res) { res.sendFile(path.join(__dirname, 'client', 'build', 'index.html')); }); // Start the server const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Server running on port ${port}`));
Key Notes
- Make sure you're sending a JSON response from your API route (I added
res.json(customers)in the example—easy to miss that!). - Double-check your frontend Fetch calls are using the correct relative URL (e.g.,
fetch('/api/customers')—since your Express server is serving both the static React files and the API, relative paths work perfectly in production). - If you have other API methods (POST, PUT, DELETE), those should also be defined before the catch-all route too—same rule applies!
内容的提问来源于stack exchange,提问作者dbhardwa

