【发布时间】:2022-08-14 23:50:24
【问题描述】:
我在 Heroku 上部署了我的第一个 MERN 堆栈应用程序,它基本上是一个酒类库存管理器。
但是它无法访问数据库。每当我拨打 Axios 电话时,我的请求都会被拒绝。我今天浪费了 7 个小时试图修复它,但无济于事。任何帮助表示赞赏。
这是我的 server.js
const express = require(\'express\')
const dotenv = require(\'dotenv\').config()
const connectDB = require(\'./config/db\')
const {errorHandler} = require(\'./middleware/errorMiddleware\')
const port = process.env.PORT || 5000
const app = express()
const path = require(\'path\')
const cors = require(\'cors\')
const mongoose = require(\'mongoose\')
connectDB()
app.use(express.json());
app.use(cors());
app.use(\'/api/users\', require(\'./routes/userRoutes\'))
app.use(\'/api/inventory\', require(\'./routes/inventoryRoutes\'))
app.use(\'/api/weekly\', require(\'./routes/weeklyRoutes\'))
mongoose.connect( process.env.MONGODB_URI, { useNewUrlParser: true })
// Serve frontend
if (process.env.NODE_ENV === \'production\') {
app.use(express.static(path.join(__dirname, \'../frontend/build\')))
app.get(\'*\', (req, res) =>
res.sendFile(
path.resolve(__dirname, \'../\', \'frontend\', \'build\', \'index.html\')
)
)
} else {
app.get(\'/\', (req, res) => res.send(\'Please set to production\'))
}
app.use(errorHandler)
app.listen(port, () => {
console.log(`Server up on ${port}`)
})
这是我的 package.json
{
\"name\": \"stockify-inventory-manager\",
\"version\": \"1.0.0\",
\"description\": \"Manage your Alcohol Inventory easily\",
\"main\": \"server.js\",
\"scripts\": {
\"start\": \"node backend/server.js\",
\"server\": \"nodemon backend/server.js\",
\"client\": \"npm start --prefix frontend\",
\"dev\": \"concurrently \\\"npm run server\\\" \\\"npm run client\\\"\",
\"heroku-postbuild\": \"NPM_CONFIG_PRODUCTION=false npm install --prefix frontend && npm run build --prefix frontend\"
},
\"author\": \"Steve Yoo\",
\"license\": \"MIT\",
\"dependencies\": {
\"bcryptjs\": \"^2.4.3\",
\"bootstrap\": \"^5.1.3\",
\"colors\": \"^1.4.0\",
\"cors\": \"^2.8.5\",
\"dotenv\": \"^16.0.0\",
\"express\": \"^4.17.3\",
\"express-async-handler\": \"^1.2.0\",
\"font-awesome\": \"^4.7.0\",
\"jsonwebtoken\": \"^8.5.1\",
\"mongoose\": \"^6.2.3\",
\"react-router-dom\": \"^6.2.1\"
}
}
以下是我尝试过的清单:
- mongoDB 上的白名单 IP 为 0.0.0.0/0
- 仔细检查来自 mongoDB 的连接字符串及其在 .env 中的设置方式
- 检查是否有任何项目卡在开发依赖项而不是依赖项中
- 仔细检查我的 Heroku 配置变量并确保它们匹配 .env
- 将 nodejs 更新到最新版本
是的,这在本地运行良好。
编辑:在 heroku local 上测试一些东西时,我注意到在本地运行的后端会导致部署的应用程序按预期工作。但是,一旦我终止本地,它就无法再次访问数据库。似乎后端在部署时甚至没有开始运行。仍然没有线索....任何帮助表示赞赏
EDIT2:添加错误截图。enter image description here
标签: javascript mongodb heroku mongoose mern