javascript - Web进程绑定(bind)$port节点失败

标签 javascript express heroku

由于某种原因,Heroku 忽略了我的 .env 文件,即使 Express 显示了要使用的端口等。我收到此错误

Web process failed to bind to $PORT within 60 seconds

我阅读了其他有关删除 dotenv 的解决方案,但如果我这样做,它会使我的应用程序崩溃。我需要 dotenv 来获取 env 变量,有没有办法为 heroku 设置 .env 或者在 heroku 上部署 Express + React + Postgress 应用程序的最佳解决方案是什么?

enter image description here

这是我的个人资料

web: node app.js

app.js

var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute  = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const PORT = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
if (!process.env.PORT) {
  require('dotenv').config()
}

// console.log(process.env.DATABASE_URL);
if (!process.env.PORT) {
  console.log('[api][port] 8000 set as default')
  console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
  console.log('[api][node] Loaded ENV vars from .env file')
  console.log(`[api][port] ${process.env.PORT}`)
  console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
require('./config/passport-github');
require('./config/passport');
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
app.use(cookieParser());
app.use(session({
  secret : process.env.JWT_SECRET,
  saveUninitialized: false,
  maxAge: 1000 * 60 * 60 * 84,
  resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false})); 
const isAuthenticated = function(req, res, next){
  if(req.isAuthenticated()){
    next();
    console.log('this works');
  }else{
   res.redirect('http://127.0.0.1:8001/signIn');
  }
}
// app.use(function(req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*');
//   // res.header('Access-Control-Allow-Credentials',  true);
//   res.header("preflightContinue", false)
//   // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
//   res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
//   next();
// });
app.use(cors({
    'allowedHeaders': ['Content-Type'], // headers that React is sending to the API
    'exposedHeaders': ['Content-Type'], // headers that you are sending back to React
    'origin': '*',
    'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
    'preflightContinue': false
}));
app.use('/api/users', userRoute );
app.use('/api/posts', isAuthenticated,  postRoute );
app.use(function(req, res, next) {
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});
models.sequelize.sync().then(() => {
  const server = app.listen(PORT, () => {
    console.log(`Server is up and running on port ${PORT}`);
  });
});

package.json

{
  "name": "sequelize-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "client": "cd ./client && npm start ",
    "server": "nodemon app.js",
    "start": "concurrently --kill-others  \"npm run client\" \"npm run server\" ",
    "heroku-postbuild": "cd client && npm install && npm run build"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "async": "^2.6.1",
    "bcrypt": "^3.0.2",
    "body-parser": "^1.18.3",
    "concurrently": "^4.1.0",
    "cookie-parser": "^1.4.3",
    "cookie-session": "^2.0.0-beta.3",
    "cors": "^2.8.5",
    "crypto": "^1.0.1",
    "dotenv": "^7.0.0",
    "express": "^4.16.4",
    "express-flash": "0.0.2",
    "express-session": "^1.15.6",
    "foreman": "^3.0.1",
    "jsonwebtoken": "^8.4.0",
    "morgan": "^1.9.1",
    "nodemailer": "^5.1.1",
    "nodemon": "^1.18.9",
    "passport": "^0.4.0",
    "passport-github": "^1.1.0",
    "passport-github2": "^0.1.11",
    "passport-jwt": "^4.0.0",
    "passport-local": "^1.0.0",
    "pg": "^7.8.0",
    "pg-hstore": "^2.3.2",
    "sequelize": "^4.42.0"
  },
  "devDependencies": {
    "chai": "^4.2.0",
    "mocha": "^6.1.2"
  }
}

config/database.js

if (!process.env.PG_DB) {
    const fs = require('fs')
    const dotenv = require('dotenv')
    const envConfig = dotenv.config({silent: true})

    // for (var k in envConfig) {
    //   process.env[k] = envConfig[k]
    // }

    console.log('[api][sequelize] Loaded database ENV vars from .env file')
  }

  module.exports = {
    development: {
      username: process.env.POSTGRES_USER,
      password: process.env.POSTGRES_PASSWORD,
      database: process.env.POSTGRES_DB,
      host: process.env.POSTGRES_HOST,
      dialect: 'postgres',
      migrationStorageTableName: 'sequelize_meta'
    },

    production: {
      username: "root",
      password: null,
      database: "*******",
      host: "127.0.0.1",
      dialect: "postgres"
    }

  }

config/config.json

{
  "development": {
    "username": "eli",
    "password": "",
    "database": "elitest4",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "postgres"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "*******",
    "host": "127.0.0.1",
    "dialect": "postgres"
  }
}

client/package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^3.9.1",
    "@material-ui/icons": "^3.0.2",
    "axios": "^0.18.0",
    "history": "^4.7.2",
    "http-proxy-middleware": "^0.19.1",
    "jsonwebtoken": "^8.4.0",
    "jwt-decode": "^2.2.0",
    "material-ui-icons": "^1.0.0-beta.36",
    "moment": "^2.24.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0",
    "react-redux": "^6.0.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.1.3",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    "superagent": "^4.1.0"
  },
  "scripts": {
    "start": "PORT=8001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postinstall": "react-scripts build"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "dotenv": "^6.2.0"
  }
}

最佳答案

这是部署到 Heroku 时的一个简单疏忽。 Heroku 管理自己的环境变量以确保它们的安全。您不应该提交您的 .env git 或任何版本控制。在 Heorkus 的情况下,只需转到应用程序仪表板的设置选项卡中,然后单击 reveal config vars并将你的 dot env 的内容放入 ui 中。 您可以使用下面的链接将您的应用程序名称放入其中,您应该会看到设置屏幕。

https://dashboard.heroku.com/apps/<your_app_name>/settings

关于javascript - Web进程绑定(bind)$port节点失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616420/

相关文章:

javascript - JQUERY PTTIMESELECT Timepicker 插件需要 Angular js 指令

mongodb - node.js + express + mongodb 任何人都尝试过使用带有副本集的express' session 管理

macos - 将行从远程控制台上的 vim 复制到 os x 剪贴板

javascript - 为什么悬停状态行为被删除?

javascript - jquery pjax + jquery Tipsy 单击后鼠标悬停时工具提示不会隐藏

javascript - 从右到左和从下到上滚动的插件

node.js - Expressjs - 文件分离和传递参数

javascript - 无法调用未定义node.js的方法 'forEach'

jquery - Heroku Assets 已上传,但图像的 URL 未更新

node.js - 检查 API 是否在 Heroku 中运行?