MEAN应用部署Heroku后/sockjs-node/info请求失败问题排查
Hey there, let's break down your problem and walk through how to fix it step by step.
First, Why This Is Happening
Heroku uses a reverse proxy to route external traffic to your app, so you never need to include the internal port (like 8817) in your frontend requests. Your issue is likely that your SockJS connection is hardcoding a port, or not dynamically adapting to the production environment's domain without a port.
Your existing webpack.dev.js proxy config won't help here—that's only for local development (it routes requests from your dev server to your backend). Once deployed to Heroku, that dev server isn't running, so those proxy rules don't apply at all. Plus, the path rewrite you set would redirect sockjs-node requests to /test, which is not what you want.
Solutions to Fix the Port Problem
1. Update SockJS Connection to Use Dynamic Origin
The simplest fix is to stop hardcoding ports and let your frontend use the current page's origin automatically. Find where you initialize SockJS in your frontend code (usually something like new SockJS('http://localhost:3000/sockjs-node')) and replace it with:
// Dynamically use the current domain (works for local dev and Heroku) const socket = new SockJS(`${window.location.origin}/sockjs-node`);
This will automatically use http://localhost:3000/sockjs-node locally, and https://sleepy-escarpment-60068.herokuapp.com/sockjs-node on Heroku—no extra port included.
2. Ensure Your Backend Listens to Heroku's PORT Variable
Double-check your Node.js backend code to make sure it's listening on the port Heroku provides via the PORT environment variable, not a fixed port:
// Backend server setup const port = process.env.PORT || 3000; // Fallback to 3000 for local dev app.listen(port, () => { console.log(`Server running on port ${port}`); });
Heroku routes external requests (without a port) to this internal port automatically, so your frontend never needs to reference it.
3. Use Webpack Environment Variables for Production (Optional)
If you want more control over production URLs, use Webpack's DefinePlugin in your production config (webpack.prod.js) to inject environment-specific values:
// webpack.prod.js const webpack = require('webpack'); module.exports = { // ... other config plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production'), 'process.env.BASE_URL': JSON.stringify('https://sleepy-escarpment-60068.herokuapp.com') }) ] };
Then in your frontend code:
const socket = new SockJS(`${process.env.BASE_URL}/sockjs-node`);
This keeps your production URL centralized and easy to update.
Quick Recap
- Your
webpack.dev.jsproxy is for local dev only—ignore it for production issues. - The core fix is removing hardcoded ports from your SockJS connection, using dynamic origin or environment variables.
- Make sure your backend listens to Heroku's
PORTvariable, not a fixed number.
内容的提问来源于stack exchange,提问作者areales

