Node.js与Angular搭建WebSocket代理失败:意外响应码404
Let's break down what's happening here and fix your issue step by step. The fact your Node proxy is triggering the upgrade event means it's catching the WebSocket handshake request, but the 404 error points to misconfigured proxy settings or missing flags the target server (echo.websocket.org) needs to accept the connection.
Step 1: Correct Your Node.js Proxy Configuration
First, let's fix the node-http-proxy setup. You need to explicitly enable WebSocket support, use the ws:// protocol for the target, and set changeOrigin (echo.websocket.org checks the request origin, which will default to localhost from your Angular app otherwise).
Working Proxy Example (Port 8014)
const http = require('http'); const httpProxy = require('http-proxy'); // Create proxy instance const proxy = httpProxy.createProxyServer({}); // Basic HTTP server for non-WebSocket requests const server = http.createServer((req, res) => { res.writeHead(404); res.end('This proxy only handles WebSocket requests'); }); // Critical: Handle WebSocket upgrade events server.on('upgrade', (req, socket, head) => { proxy.ws(req, socket, head, { target: 'ws://echo.websocket.org', // Use ws:// protocol, not http:// changeOrigin: true, // Fixes origin mismatch issues with the target server ws: true // Explicitly enable WebSocket proxying }); }); // Log proxy errors for debugging proxy.on('error', (err, req, res) => { console.error('Proxy error:', err); }); server.listen(8014); console.log('WebSocket proxy running on port 8014');
Alternative: Simple Proxy with ws Module (Port 8015)
If you want a more transparent, easier-to-debug setup, use the ws module directly instead of node-http-proxy:
const http = require('http'); const WebSocket = require('ws'); const server = http.createServer((req, res) => { res.writeHead(404); res.end(); }); // Create WebSocket server for your Angular app const wss = new WebSocket.Server({ server }); wss.on('connection', (clientWs) => { // Connect to the target echo server const targetWs = new WebSocket('ws://echo.websocket.org'); // Forward messages from Angular to echo server clientWs.on('message', (data) => { targetWs.send(data); }); // Forward echo server responses back to Angular targetWs.on('message', (data) => { clientWs.send(data); }); // Clean up connections on close/error clientWs.on('close', () => targetWs.close()); targetWs.on('close', () => clientWs.close()); clientWs.on('error', (err) => console.error('Client WS error:', err)); targetWs.on('error', (err) => console.error('Target WS error:', err)); }); server.listen(8015); console.log('Simple WebSocket proxy running on port 8015');
Step 2: Update Your Angular WebSocket Connection
Make sure your Angular code connects to the proxy, not directly to echo.websocket.org:
// Replace your existing WebSocket connection line with this const socket = new WebSocket('ws://localhost:8014'); // Use 8015 for the ws module proxy // Keep your existing event handlers socket.onopen = () => { console.log('Connected to proxy'); socket.send('Hello from Angular via proxy!'); }; socket.onmessage = (evt) => { console.log('Echo response:', evt.data); }; socket.onerror = (evt) => { console.error('WebSocket error:', evt); };
Step 3: Debugging Checks
If you still get 404s:
- Check Chrome DevTools: Go to the Network tab, filter for "WS", click the WebSocket request, and inspect the Request/Response Headers. If the target server rejects the origin, you'll see clues here.
- Check Node Console: The proxy error logs (added in the first example) will tell you if there's a connection issue to
echo.websocket.org. - Verify Target URL: Ensure you're using
ws://echo.websocket.org(nothttp://orwss://—echo.websocket.org uses unencrypted WS by default).
内容的提问来源于stack exchange,提问作者Semicolons and Duct Tape




