如何解决create-react-app构建应用无法被局域网设备访问的问题?
Hey there, let's troubleshoot why your create-react-app (CRA) build isn't accessible from other devices on your LAN—even though other React projects work fine with http-server. These are the most common fixes to get things working:
1. Force your server to listen on all network interfaces
By default, tools like http-server often bind only to 127.0.0.1 (localhost), which means they won't accept requests from other devices on the network. To fix this, explicitly tell the server to listen on 0.0.0.0 (all available network interfaces):
For http-server:
http-server build -a 0.0.0.0 -p 3000
-a 0.0.0.0: Binds the server to all your device's network adapters-p 3000: Uses port 3000 (replace with any unused port if needed)
After running this, access the app from other devices using your host device's LAN IP (e.g., http://192.168.1.100:3000).
2. Fix your CRA homepage configuration
CRA's homepage setting in package.json can break LAN access if it's configured incorrectly:
- If you have
"homepage": "http://localhost:3000"set, other devices will try to load static resources from their ownlocalhost(which doesn't have the app), leading to broken assets. - Even a relative path like
"homepage": "./"can cause issues if you're usingBrowserRouter(since it relies on server-side pushstate handling).
Solutions:
- Remove the
homepagefield entirely: CRA defaults to serving from the root path, which works perfectly with http-server when bound to0.0.0.0. - If you need a relative path: Use
"homepage": "."and switch toHashRouterinstead ofBrowserRouter(HashRouter doesn't require server-side configuration for routing). - For BrowserRouter users: Keep
homepageunset, and add the-Pflag to http-server to handle pushstate routing:
This forwards all 404 requests tohttp-server build -a 0.0.0.0 -p 3000 -P http://localhost:3000index.html, which is required for SPA routes to work.
3. Correct pushstate-server usage
If you're using pushstate-server (the recommended tool for CRA builds), make sure you specify the listen address explicitly. Many versions default to 127.0.0.1, so run:
pushstate-server build 3000 0.0.0.0
The third argument (0.0.0.0) tells the server to accept connections from all devices on the LAN.
4. Rule out firewall/network issues
Even if other projects work, double-check these:
- Ensure your host device's firewall allows incoming connections on the port you're using (e.g., 3000). On Windows, check Windows Defender Firewall; on Mac, go to System Settings > Network > Firewall.
- Confirm all devices are on the same LAN (same subnet, e.g.,
192.168.1.x). You can find your host device's LAN IP by runningipconfig(Windows) orifconfig/ip addr(Mac/Linux).
Start with steps 1 and 2—they're the most likely culprits. Once you've applied those, your CRA build should be accessible from any device on your network!
内容的提问来源于stack exchange,提问作者Stramike

