我部署了一个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密钥和其他凭据?以下是最佳实践: