繁体   English   中英

无法从 heroku 应用程序访问 mongoodb 数据库

[英]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)

谁能告诉我:)。

我正在回答我的问题,我觉得将来可能有人会遇到同样的问题,所以他们可以通过以下简单的步骤来解决它:

  1. 您必须访问 heroku 网站并单击您创建的应用程序上的选项。
  2. 现在他们你必须去设置选项并在配置字段中添加你的 .env 键和值。
  3. 确保您像我所做的那样从 axios 采取正确的路径。
  4. 如果应用程序仍然没有显示数据库资料,那么再次转到 heroku,您将在右侧看到“更多”选项卡,您必须重新启动 dynos。

希望你能得到想要的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM