运行Angular项目时遭遇WebSocket连接错误,求解决方案
Hey there, let's work through this frustrating WebSocket issue you're hitting with your Angular project—those 400 handshake errors in Chrome and WDS disconnections in Firefox are totally fixable, so here are some tried-and-tested steps to get you back on track:
Common Troubleshooting Solutions
1. Verify Local Host & Dev Server Settings
- If you’re using
admin.petnpals.comfor local development, first confirm this domain is mapped to127.0.0.1in your system’shostsfile (found atC:\Windows\System32\drivers\etc\hostson Windows or/etc/hostson Mac/Linux). - Check your
angular.jsonfile’sserveconfiguration: make sure thehostis set to0.0.0.0orlocalhost, andpublicHost(if specified) matches the domain you’re accessing. - If you’ve customized your Webpack config, try adding
disableHostCheck: trueto thedevServersection (note: this is a dev-only workaround—never use it in production!).
2. Fix Proxy Configuration (If Applicable)
If your project uses a proxy (via proxy.conf.json), ensure it doesn’t block the /sockjs-node/ path required for Webpack Dev Server (WDS) connections. Update your proxy config like this:
{ "/api": { "target": "http://your-backend-api-url", "secure": false }, "/sockjs-node": { "target": "http://localhost:4200", "secure": false, "ws": true, "bypass": (req) => { if (req.headers.accept?.includes("html")) { return "/index.html"; } } } }
Then start your server with the proxy flag:
ng serve --proxy-config proxy.conf.json
3. Clear Browser Cache & Restart Dev Server
- Old cached connection data can cause handshake failures. Clear your browser’s full cache (Chrome: Ctrl+Shift+Del, select "All time" and check "Cached images and files"; Firefox: Ctrl+Shift+Del, check "Cache") and restart the browser.
- Stop your
ng serveprocess, kill any leftover node processes, then restart the dev server. You can also test with live reload disabled temporarily:
ng serve --live-reload=false
4. Check Network & Port Availability
- Corporate firewalls or network restrictions often block WebSocket connections. Try switching to a personal hotspot or temporarily disabling your firewall to rule this out.
- Confirm the default Angular port (4200) isn’t occupied by another app:
- Windows:
netstat -ano | findstr :4200 - Mac/Linux:
lsof -i :4200
If it’s taken, start the server on a different port:
- Windows:
ng serve --port 4201
5. Update Dependencies
Outdated versions of Angular CLI, Webpack Dev Server, or SockJS can cause compatibility issues. Try updating your dependencies:
npm update @angular/cli webpack-dev-server sockjs-client
If that doesn’t work, delete your node_modules folder and package-lock.json file, then run npm install for a clean dependency install.
Hope one of these fixes gets your project running smoothly again! Feel free to follow up if you need more details on any step.
内容的提问来源于stack exchange,提问作者Manisha

