Heroku错误:ENOENT:没有这样的文件或目录,请打开".env" [英] Heroku Error: ENOENT: no such file or directory, open '.env'

查看:75
本文介绍了Heroku错误:ENOENT:没有这样的文件或目录,请打开".env"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to push my application to Heroku, but I'm running into some issues:

错误: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)

Error: ENOENT: no such file or directory, open '.env' 2019-04-10T01:38:23.050188+00:00 app[web.1]: 1 at Object.openSync (fs.js:438:3) 2019-04-10T01:38:23.050190+00:00 app[web.1]: 1 at Object.readFileSync (fs.js:343:35) 2019-04-10T01:38:23.050192+00:00 app[web.1]: 1 at Object. (/app/config/database.js:4:39)

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

It seems that the error is the variable envConfig, but i need it for database to work.

截至目前,我正在得到

这是我的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}`);
  });
});

推荐答案

在执行其他任何操作之前,如果这些是您的真实凭据,则应 立即 使它们失效.他们是永远的 受到损害,则需要生成新的. 不够 来对它们进行修改.

Before you do anything else, if those are your real credentials you should invalidate them immediately. They are forever compromised, and you need to generate new ones. Editing them out of your question is not enough.

您可以更改

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

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

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

You don't need to manually read the file here, and skipping it lets you gracefully handle the case when it doesn't exist. There's also no need to manually set values in process.env:

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

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

This can be entirely skipped. Dotenv takes care of this itself. Therefore, you don't need envConfig either, reducing all of that to just

dotenv.config({silent: true})

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

If .env exists, its contents will be added to what's already in process.env. In development, this gives you a convenient way to set your database connection information.

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

In production, .env shouldn't exist, and your database connection information definitely shouldn't be hard-coded. Instead, your database connection information should come from one or more Heroku config vars (these are environment variables that should already be available via process.env). Your database addon has probably already set the DATABASE_URL variable for you.

对于.env中已设置的内容,请为其生产值设置一个Heroku配置变量.您可以通过Heroku Web仪表板或通过 Heroku CLI :

For things in your .env that you've set yourself, set a Heroku config var for its production value. You can do that through the Heroku web dashboard or via the Heroku CLI:

heroku config:set SOME_VARIABLE=foo

这篇关于Heroku错误:ENOENT:没有这样的文件或目录,请打开".env"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆