Heroku后端服务器部署后运行报错:ReferenceError: PORT is not defined 求助
Hey there, let's work through this PORT error you're facing—even though your code looks correct, there are a few common culprits to check:
1. Double-Check Variable Scope
The error tells us PORT isn’t accessible where app.listen() is running. Make sure your const PORT = process.env.PORT || 8080 line lives in the same top-level scope as the app.listen call. For example, if you accidentally wrapped the PORT definition inside a function or conditional block like this:
function initServer() { const PORT = process.env.PORT || 8080; } // app.listen is outside the function, so PORT is undefined here app.listen(PORT, () => { ... });
Move the PORT declaration to the top of your file, before any app.listen calls, so it’s available everywhere it’s needed.
2. Verify Environment Variable Spelling/Case
Heroku automatically sets the PORT environment variable in all uppercase. While your code looks right, double-check for typos (like process.env.port with a lowercase "p")—a tiny mistake here could break the variable lookup on Heroku even if it works locally.
3. Check Cross-File Variable Access
If your app.listen() is in a different file than where you define PORT, you need to properly export and import the variable. For example:
- In your entry file (e.g.,
server.js):const PORT = process.env.PORT || 8080; module.exports = { PORT }; - In the file with
app.listen:const { PORT } = require('./server.js'); app.listen(PORT, () => { ... });
Without this export/import step, the second file won’t recognize the PORT variable.
4. Force a Fresh Heroku Rebuild
Sometimes Heroku caches old build artifacts, which might be running an outdated version of your code where PORT wasn’t defined. Trigger a full rebuild by pushing an empty commit:
git commit --allow-empty -m "Force Heroku rebuild" git push heroku main
This will make Heroku recompile your app from scratch, ensuring it uses your latest code.
Give these steps a try—one of them should get your app up and running!
内容的提问来源于stack exchange,提问作者AmmanM

