部署 mongodb 和快速项目时出错
Error on deploying mongodb and express project
我正在部署具有猫鼬连接的 Express 应用程序。在本地主机上一切正常。但是当我部署到 heroku 时,我收到状态为 503 的错误“应用程序错误”。
当我尝试在没有 mongoose 连接的情况下进行部署时,我的应用程序在 heroku 服务器上运行良好。所以我知道问题可能出在 mongoose 连接上。
index.js 代码的 mongoose 连接部分(不适用于 heroku):
app.get("/", (req, res) => {
res.send(`Server launched perfectly!`);
});
const PORT = process.env.PORT || 5000;
mongoose.connect(process.env.CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.connect(process.env.CONNECTION_URL).then(()=>{console.log('...')});
index.js 没有 mongoose 连接(在 heroku 上完美运行):
app.get("/", (req, res) => {
res.send(`Server launched perfectly!`);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`));
这可能是一个不同的问题,但 Procfile 和 package.json 没问题。
连接应该是异步的,你可以这样创建一个函数:
const connect = async () => {
try {
const db = await mongoose.connect(DB_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
});
const { name, host } = db.connection;
console.log(`Conección correcta a la base de datos ${name} en ${host}`);
} catch(error) {
console.log('Problemas al conectarse a la DB. Error ->', error);
}
};
我正在部署具有猫鼬连接的 Express 应用程序。在本地主机上一切正常。但是当我部署到 heroku 时,我收到状态为 503 的错误“应用程序错误”。
当我尝试在没有 mongoose 连接的情况下进行部署时,我的应用程序在 heroku 服务器上运行良好。所以我知道问题可能出在 mongoose 连接上。
index.js 代码的 mongoose 连接部分(不适用于 heroku):
app.get("/", (req, res) => {
res.send(`Server launched perfectly!`);
});
const PORT = process.env.PORT || 5000;
mongoose.connect(process.env.CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.connect(process.env.CONNECTION_URL).then(()=>{console.log('...')});
index.js 没有 mongoose 连接(在 heroku 上完美运行):
app.get("/", (req, res) => {
res.send(`Server launched perfectly!`);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`));
这可能是一个不同的问题,但 Procfile 和 package.json 没问题。
连接应该是异步的,你可以这样创建一个函数:
const connect = async () => {
try {
const db = await mongoose.connect(DB_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
});
const { name, host } = db.connection;
console.log(`Conección correcta a la base de datos ${name} en ${host}`);
} catch(error) {
console.log('Problemas al conectarse a la DB. Error ->', error);
}
};