在我使用Heroku部署MERN应用程序后,mongoDB无法工作,而该应用程序在我的本地主机上运行良好



由于这个问题,我已经扯了几个小时的头发…:(

该应用程序在我的本地主机上运行良好,但mongoDB似乎没有连接到我的应用程序。

它一直给我一个";类型错误";我认为它没有得到mongoDB的回应。

这是我在后台目录中的index.js文件,.env文件与index.js.在同一目录中


// backend/index.js
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const app = express();
const pinRoute = require("./routes/pins");
const userRoute = require("./routes/users");
const path = require("path")
dotenv.config();
app.use(express.json());
const uri = process.env.MONGO_URL;
console.log(uri)
// console.log does show uri.
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
console.log("MongoDB Connected :)");
})
.catch((err) => console.log(err));
app.use("/api/pins", pinRoute);
app.use("/api/users", userRoute);
if (process.env.NODE_ENV === "production") {
app.use(express.static("frontend/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "../frontend", "build", "index.html"))
})
}
const port = process.env.PORT || 8800;
app.listen(port, () => {
console.log(`Backend server is running at ${port} :)`);
});

这是我的包.json


// this is in the root directory.
{
"name": "backend",
"version": "1.0.0",
"main": "backend/index.js",
"license": "MIT",
"engines": {
"node": "14.15.4",
"yarn": "1.22.10"
},
"scripts": {
"start": "node backend/index.js",
"backend": "nodemon backend/index.js",
"frontend": "cd frontend && yarn start",
"heroku-postbuild": "cd frontend && yarn install && yarn build ",
"build": "cd frontend && yarn build"
},
"dependencies": {
"bcrypt": "^5.0.1",
"dotenv": "^9.0.2",
"express": "^4.17.1",
"mongoose": "^5.12.8",
"nodemon": "^2.0.7"
}
}

这就是我得到的错误。。。

1.尝试使用环境变量名作为mongoose.connect的参数,看看它是否有效。您不需要像这样将值分配给uri常量。

mongoose
.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
.then(() => {
console.log("MongoDB Connected);
})
.catch((err) => console.log(err));
  1. 你可以在你的基本URL中添加一条路由,当你点击相同的URL时,它会给你一个响应。

    app.get("/", (req, res) => {
    res.send("Default Route Works!");
    })
    

编辑:

无论何时重定向到,都可以将其添加到中间件下方的app.js中

http://localhost:PORT/
eg. http://localhost:8080/    GET Request

你应该看到消息";默认路线有效"在屏幕上。或者,您可以通过Insomnia或POSTMAN等API客户端向同一个端点发送GET请求。

注意:请将您的端口号更改为localhost地址中显示port的位置。

最新更新