我正在部署具有貓鼬連接的快速應用程式。在本地主機上一切正常。但是當我部署到 heroku 時,我收到一個狀態為 503 的錯誤“應用程式錯誤”。
當我嘗試在沒有貓鼬連接的情況下進行部署時,我的應用程式在 heroku 服務器上運行良好。所以我發現問題可能出在貓鼬連接上。
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(在 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 很好。
uj5u.com熱心網友回復:
連接應該是異步的,你可以創建一個這樣的函式:
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);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347935.html
