Heroku错误:无法找到模块'./config/keys'

3

我部署了一个Nodejs应用程序,目前将其后端部署到Heroku。在浏览器中出现了应用程序错误。当我运行heroku logs时,我看到了这个错误:

Error: Cannot find module './config/keys'

我运行了heroku run 'ls -al',然后看到了以下内容:

Running ls -al on ⬢ murmuring-temple-46226... up, run.3327 (Free)
total 284
drwx------   8 u6811 dyno   4096 Apr 21 11:41 .
drwxr-xr-x  15 root  root   4096 Apr 18 13:09 ..
-rw-------   1 u6811 dyno     21 Apr 21 11:37 .gitignore
drwx------   3 u6811 dyno   4096 Apr 21 11:37 .heroku
drwx------   2 u6811 dyno   4096 Apr 21 11:37 .profile.d
-rw-------   1 u6811 dyno      0 Apr 21 11:37 @1
-rw-------   1 u6811 dyno    574 Apr 21 11:37 index.js
drwx------   2 u6811 dyno   4096 Apr 21 11:37 models
drwx------ 261 u6811 dyno  12288 Apr 21 11:38 node_modules
-rw-------   1 u6811 dyno 235090 Apr 21 11:37 package-lock.json
-rw-------   1 u6811 dyno    565 Apr 21 11:37 package.json
drwx------   2 u6811 dyno   4096 Apr 21 11:37 routes
drwx------   2 u6811 dyno   4096 Apr 21 11:37 services

我发现我的 `config` 文件夹没有出现在上面的文件和文件夹列表中,但这可能是由于我在我的 `.gitignore` 文件中设置了忽略 `keys.js` 文件,或者是因为我在代码库中引用错误吗?
这是我在 `index.js` 中如何引用它的:
const express = require('express');
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');

mongoose.connect(keys.mongoURI);

const app = express();

app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.cookieKey]
  })
);
app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

这是我在services/passport.js中引用它的方式:

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const mongoose = require('mongoose');
const keys = require('../config/keys');

const User = mongoose.model('users');

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    done(null, user);
  });
});

// passport.use() is a generic register to make Passport
// aware of new strategy
// creates a new instance to authenticate users
passport.use(
  new GoogleStrategy(
    {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: '/auth/google/callback'
    },
    (accessToken, refreshToken, profile, done) => {
      User.findOne({ googleId: profile.id }).then(existingUser => {
        if (existingUser) {
          // we already have a record with given profile id
          done(null, existingUser);
        } else {
          // we dont have a user record with this id, make a new record
          new User({ googleId: profile.id })
            .save()
            .then(user => done(null, user));
        }
      });
    }
  )
);

如何在Heroku上成功部署一个应用程序并使用config/keys.js文件夹结构来存储API密钥和其他凭据?以下是最佳实践:

2个回答

2
我会将keys.js从你的.gitignore文件中移除。在你的config文件夹中创建另外两个文件,一个用于开发环境,另一个用于生产环境,把你的密钥放在开发文件中,并让.gitignore忽略这个开发文件。
然后在你的keys.js文件中创建一个if语句,例如:
// keys.js - figure out what set of credentials to return
if (process.env.NODE_ENV === 'production') {
  // we are in production - return the prod set of keys
  module.exports = require('./prod');
} else {
  // we are in development - return the dev keys!!
  module.exports = require('./dev');
}

在您的生产文件中,您将按照我上面同事的建议进行操作,但可能更像这样:
// prod.js - production keys here
module.exports = {
  googleClientID: process.env.GOOGLE_CLIENT_ID,
  googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,
  cookieKey: process.env.COOKIE_KEY
};

如果您同时连接到像MongoDB这样的数据库,那么您需要像以下这样添加它:mongoURI: process.env.MONGO_URI
最后你需要确保在你的Heroku环境变量中定义了所有这些不同的环境变量。设置所有这些东西非常简单,你只需要知道在Herokus'控制界面上查找的位置或者像我上面的同事建议的那样通过命令行终端进行操作。如果你对命令行终端非常熟悉,那就按照以上步骤操作,否则进入浏览器并导航至dashboard.heroku.com。
找到你为应用程序创建的应用程序,点击它。然后点击设置选项卡,你应该会看到配置变量。单击显示配置变量,这将为您提供一个接口来设置您想要添加到应用程序中的所有不同变量。
一次添加一个键和其相应的值,所以首先做GOOGLE_CLIENT_ID,复制它并将其输入为密钥,然后获取您的凭据。您应该已经在某个地方复制粘贴了您的凭据。对于COOKIE_KEY和如果您使用Mongo,则是MONGO_URI也是如此。
现在你可以隐藏配置变量,没人能看到它们。正如你可能想象的那样,你不希望任何人进入你的Heroku账户。如果有人进入了您的Heroku账户,我也不知道该怎么办了。
现在你可以通过使用git提交你的代码并使用git部署应用程序。执行git status查看您的文件和文件夹。执行git add .git commit -m "completed environment variables"git pushgit push heroku master
这样做后,您就可以顺利启动应用程序,而错误也将消失。

1

你做得对,忽略了配置文件。你应该始终将秘密密钥远离github和bitbucket。在这种情况下的正确方法是将你的密钥设置为heroku上的环境变量。你可以使用以下命令:

# Add new variable
heroku config:set COOKIE_KEY=somekey

# Remove variable
heroku config:unset COOKIE_KEY

# Get all environment variables
heroku config

# Get environment variable by name
heroku config:get COOKIE_KEY

在您的应用程序中,您可以使用process.env对象访问这些变量:
process.env.COOKIE_KEY
process.env.GOOGLE_CLIENT_ID
process.env.GOOGLE_CLIENT_SECRET

注意:配置键必须大写。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接