[英]Unable to access mongoodb database from heroku application
大家好,我正在开发简单的 mern 应用程序,我知道对于所有优秀的开发人员来说这将是一个愚蠢的问题,但是在我的 mern 应用程序中,当我在本地主机上运行时,它可以很好地发送和获取数据,但是当我将它托管在 heroku 上时,最初它工作正常,但一段时间后它无法获取和发布请求。
索引.js:
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const usersRouter = require("./routes/users");
const exercisesRouter = require("./routes/exercises");
const app = express();
require("dotenv").config();
const path = require("path");
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.MONGODB_CONNECTION_STRING,
{useNewUrlParser : true}).then(() => console.log("Database is Connected"))
.catch(err => console.log("error occcured"));
app.use("/users", usersRouter);
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
// app.use(express.static(path.resolve(__dirname, "./client/build")));
// app.get("*", function (request, response) {
// response.sendFile(path.resolve(__dirname, "./client/build", "index.html"));
// });
const PORT = process.env.PORT || 5000;
app.listen(PORT , () => {
console.log(`app is running on :${PORT}`);
});
包.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"client-build": "cd client && npm run build",
"client-install": "cd client && npm install",
"heroku-postbuild": "npm run client-install && npm run client-build",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"mongoose": "^6.3.3",
"nodemon": "^2.0.16"
},
"engines": {
"node": "14.17.3"
}
}
我在前面使用 Axios:
axios.post('https://workouttrackergoal.herokuapp.com/add', user)
谁能告诉我:)。
我正在回答我的问题,我觉得将来可能有人会遇到同样的问题,所以他们可以通过以下简单的步骤来解决它:
希望你能得到想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.