Heroku错误:ENOENT:没有此类文件或目录,请打开“ .env”

时间:2019-04-10 01:44:03

标签: javascript node.js express heroku

我试图将应用程序推送到Heroku,但是遇到了一些问题:

  

错误:ENOENT:没有此类文件或目录,请打开“ .env”   2019-04-10T01:38:23.050188 + 00:00 app [web.1]:1在   Object.openSync(fs.js:438:3)2019-04-10T01:38:23.050190 + 00:00   app [web.1]:1,位于Object.readFileSync(fs.js:343:35)   2019-04-10T01:38:23.050192 + 00:00 app [web.1]:1在   宾语。 (/app/config/database.js:4:39)

似乎错误是变量envConfig,但我需要它才能使数据库正常工作。

截至目前,我正在得到

enter image description here

这是我的config/database.js

if (!process.env.PG_DB) {
    const fs = require('fs')
    const dotenv = require('dotenv')
    // dotenv, but i need this make the database work
    const envConfig = dotenv.parse(fs.readFileSync('.env'))

    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: "*********some postgress url",
      host: "127.0.0.1",
      dialect: "postgres"
    }

还有我的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()
}
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(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}`);
  });
});

1 个答案:

答案 0 :(得分:1)

在执行其他任何操作之前,如果这些是您的真实凭据,则应 立即 使它们失效。他们永远 遭到入侵,则需要生成新的。 不够


您可以更改

const envConfig = dotenv.parse(fs.readFileSync('.env'))

const envConfig = dotenv.config({silent: true})

您无需在此处手动读取文件,而跳过它可以让您在不存在文件的情况下优雅地处理该文件。也无需手动在process.env中设置值:

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

可以完全跳过。 Dotenv会自行处理。因此,您也不需要envConfig,只需将所有内容简化为

dotenv.config({silent: true})

如果.env存在,其内容将添加到process.env中已有的内容中。在开发中,这为您提供了一种方便的方法来设置数据库连接信息。

在生产中,.env不应该存在,并且您的数据库连接信息绝对不应进行硬编码。相反,您的数据库连接信息应来自一个或多个Heroku config vars(这些环境变量应该已经可以通过process.env使用)。您的数据库插件可能已经为您设置了DATABASE_URL变量。

对于.env中已设置的内容,请为其生产值设置一个Heroku配置变量。您可以通过Heroku网络信息中心或通过Heroku CLI来做到这一点:

heroku config:set SOME_VARIABLE=foo