无法通过本地主机(MAMP)访问React应用的问题求助
Hey there, let's work through this problem step by step. I see you've set up React Router with a basename="/api" and can't access your app via MAMP—here are the most likely fixes to get you up and running:
1. Double-Check Your Access URL & Environment
First, clarify whether you're running your app in development mode (using npm start) or serving a production build (static files in MAMP's htdocs):
- Development mode: The React dev server runs on port 3000 by default. You don't need to go through MAMP's port (usually 8888) here—just visit
http://localhost:3000/api/bonus/[your-id]orhttp://localhost:3000/api/historyBonusdirectly. - Production build: If you've built your app with
npm run buildand moved thebuildfolder into MAMP'shtdocsdirectory, make sure your URL matches thebasenameand folder structure. For example:- If you placed the
buildfolder insidehtdocs/api, visithttp://localhost:8888/api/bonus/[your-id] - If the
buildfolder is directly inhtdocs, you probably don't need thebasename="/api"—remove it or adjust your URL tohttp://localhost:8888/bonus/[your-id]
- If you placed the
2. Fix Frontend Routing Refresh Issues (For Production Builds)
When using BrowserRouter, refreshing a route (like /api/bonus/123) will cause MAMP's Apache server to look for a physical file at that path—which doesn't exist. To fix this, create a .htaccess file in your React app's root folder (inside MAMP's htdocs directory) with these rewrite rules:
Options -MultiViews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.html [QSA,L]
This tells Apache to redirect all non-file/non-directory requests to index.html, letting React Router handle the routing.
3. Verify MAMP's Document Root Configuration
Make sure MAMP is pointing to the correct directory:
- Open MAMP, go to Preferences > Web Server
- Check that the "Document Root" is set to the folder containing your React build files (e.g.,
htdocs/apiif you're using the/apibasename) - Restart MAMP after making changes
4. Validate Route Paths & exact Prop
Your routes use the exact prop, so make sure your URLs match exactly:
- For
BonusScreen, you need to include an ID in the URL:http://localhost:[port]/api/bonus/123(not just/api/bonus) - For
HistoryBonus, the URL should be exactlyhttp://localhost:[port]/api/historyBonus(no extra slashes or characters)
内容的提问来源于stack exchange,提问作者kurniawan26

