gpt4 book ai didi

javascript - 将应用程序部署到 Heroku,ENV 变量不起作用

转载 作者:行者123 更新时间:2023-12-04 07:49:54 30 4
gpt4 key购买 nike

我最近将我的 Node js 应用程序部署到 Heroku,但在让我的应用程序运行时遇到了一些问题。我的应用程序已加载,但当我尝试登录时它中断了。据我所知,环境变量由于某种原因没有正确加载。 db 变量是从我的 .ENV 文件中获取的字符串,是用于连接到 mongo db 的 Monogo URI。出于某种原因,当 heroku 运行它时,process.env.MongoURI 未定义。有人知道为什么会这样吗?

我遇到的具体错误是。

错误

MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

应用程序.js

/* eslint-disable no-unused-vars */
/* eslint-disable comma-dangle */
/* eslint-disable no-console */
/* eslint-disable arrow-parens */
const createError = require('http-errors');
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const dotenv = require('dotenv');

dotenv.config();

const indexRouter = require('./server/index');

const port = process.env.PORT || 3000;
const app = express();

require('./server/config/passport')(passport);

// DB Config
const db = process.env.MongoURI;

mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true }) // I beleieve this is the line that is breaking the code.
.then(() => { console.log('MONGODB Connected'); })
.catch(err => console.log(err));

app.use(expressLayouts);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

app.use(flash());

app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

app.listen(port, () => {
console.log(`Running on port ${port}`);
});

module.exports = app;

最佳答案

为此,您可能应该使用 Heroku 的内置环境变量编辑器。

关于javascript - 将应用程序部署到 Heroku,ENV 变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67038663/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com