Web进程无法绑定$ port节点

时间:2019-04-10 15:34:20

标签: javascript express heroku

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

  

Web进程在60秒内未能绑定到$ PORT

我阅读了其他有关删除var=for item in output: v=''.join(item) link="https://example.com/user/{}".format(v) print(link) 的解决方案,但是如果这样做,它将使我的应用程序崩溃。我需要dotenv来获取env变量,是否可以为heroku设置.env,或者在heroku上部署express + react + postgress应用程序的最佳解决方案是什么?

enter image description here

这是我的个人资料

dotenv

app.js

web: node app.js

package.json

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}`);
  });
});

config / database.js

{
  "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 / config.json

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"
    }

  }

client / package.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"
  }
}

1 个答案:

答案 0 :(得分:1)

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

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