【问题标题】:MERN-Stack Heroku - Cannot GET /MERN-Stack Heroku - 无法获取 /
【发布时间】:2021-03-30 04:47:47
【问题描述】:

尝试在 Heroku 上部署 MERN-Stack 我在 Heroku 上的 Config Vars 中添加了 MONGOBD_URI 作为键,并添加了 MongoDB Atlas 值。

Heroku 直接连接到 Github 存储库,而不是通过 Heroku CLI。我已将其设置为自动部署,但最近手动重新部署了它。

这是 Heroku 构建日志:

-----> Node.js app detected
       
-----> Creating runtime environment
       
       NPM_CONFIG_LOGLEVEL=error
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       
-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)
       
       Resolving node version 12.x...
       Downloading and installing node 12.20.0...
       Using default npm version: 6.14.8
       
-----> Restoring cache
       Cached directories were not restored due to a change in version of node, npm, yarn or stack
       Module installation may take longer for this build
       
-----> Installing dependencies
       Installing node modules
       
       > nodemon@2.0.6 postinstall /tmp/build_b41198ca_/node_modules/nodemon
       > node bin/postinstall || exit 0
       
       Love nodemon? You can now support the project via the open collective:
        > https://opencollective.com/nodemon/donate
       
       added 290 packages in 6.983s
       
-----> Build
       
-----> Caching build
       - node_modules
       
-----> Pruning devDependencies
       removed 1 package and audited 289 packages in 2.051s
       
       17 packages are looking for funding
         run `npm fund` for details
       
       found 0 vulnerabilities
       
       
-----> Build succeeded!
-----> Discovering process types
       Procfile declares types     -> (none)
       Default types for buildpack -> web
-----> Compressing...
       Done: 33M
-----> Launching...
       Released v17
       https://jms-r0b.herokuapp.com/ deployed to Heroku

浏览器(Chrome)只呈现Cannot GET /consol.log()的GET https://jms-r0b.herokuapp.com/ 404 (Not Found) jms-r0b.herokuapp.com/:1

这是我的仓库的LINK

以下是我的 server.js 的设置方式:

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const todoRoutes = express.Router();
const PORT = process.env.PORT || 4000;

let Todo = require("./models/todo.model");

app.use(cors());
app.use(bodyParser.json());

// Express data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));

const URI = process.env.MONGODB_URI || "mongodb://localhost/todos";
mongoose.connect(
  URI,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  },
  (err) => console.log(err)
);
const connection = mongoose.connection;

connection.once("open", () => {
  console.log("MongoDB database connection established successfully");
});

todoRoutes.route("/").get((req, res) => {
  Todo.find((err, todos) => {
    if (err) {
      console.log(err);
    } else {
      res.json(todos);
    }
  });
});

todoRoutes.route("/:id").get((req, res) => {
  let id = req.params.id;
  Todo.findById(id, (err, todo) => {
    res.json(todo);
  });
});

todoRoutes.route("/update/:id").post((req, res) => {
  Todo.findById(req.params.id, (err, todo) => {
    if (!todo) {
      res.status(404).send("data is not found");
    } else {
      todo.todo_description = req.body.todo_description;
      todo.todo_responsible = req.body.todo_responsible;
      todo.todo_priority = req.body.todo_priority;
      todo.todo_completed = req.body.todo_completed;

      todo
        .save()
        .then((todo) => {
          res.json("Todo updated!");
        })
        .catch((err) => {
          res.status(400).send("Update not possible");
        });
    }
  });
});

todoRoutes.route("/add").post((req, res) => {
  let todo = new Todo(req.body);
  todo
    .save()
    .then((todo) => {
      res.status(200).json({ todo: "todo added successfully" });
    })
    .catch((err) => {
      res.status(400).send("adding new todo failed");
    });
});

todoRoutes.route("/delete/:id").delete((req, res) => {
  Todo.findByIdAndRemove(req.params.id, (err, todo) => {
    if (!todo) {
      res.status(404).send("data is not found");
    } else {
      res.status(200).json({
        msg: todo,
      });
    }
  });
});

app.use("/todos", todoRoutes);

app.listen(PORT, () => {
  console.log("http://localhost:" + PORT);
  console.log(".env.PORT:" + process.env.PORT);
});

这就是我的 root package.json 的样子:

{
  "name": "rob",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start:dev": "cd client && npm start",
    "client": "cd client && npm run start",
    "start": "concurrently \"node server/server.js\" \"npm run client\"",
    "dev": "concurrently \"nodemon server/server.js\" \"npm run client\""
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/WasteOfADrumBum/r0b.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/WasteOfADrumBum/r0b/issues"
  },
  "homepage": "https://github.com/WasteOfADrumBum/r0b#readme",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "concurrently": "^5.3.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-mongo-sanitize": "^2.0.0",
    "express-rate-limit": "^5.1.3",
    "helmet": "^4.2.0",
    "hpp": "^0.2.3",
    "ini": "^2.0.0",
    "mongoose": "^5.10.13",
    "nodemon": "^2.0.6",
    "react": "^17.0.1",
    "react-cool-onclickoutside": "^1.5.8",
    "react-dom": "^17.0.1",
    "validator": "^12.0.0",
    "xss-clean": "^0.1.1"
  },
  "devDependencies": {
    "dotenv": "^8.2.0"
  }
}

我需要一点帮助。我已经部署了 5 个其他带有 MongoDB Atlas 或 JawsDB 连接的 MERN-Stacks,几乎没有问题,而这个只是让我陷入困境。

请帮忙!!!

【问题讨论】:

    标签: github heroku web-deployment mern mongodb-atlas


    【解决方案1】:

    每个人的做法都不一样,但我认为错误在于您与 MongDB 的连接——您建立连接是否正常?

    如果没有连接 - 你说“我在 Heroku 上的 Config Vars 中添加了 MONGOBD_URI 作为键,并添加了 MongoDB Atlas 值。”但是我看到您的代码中没有使用“config Vars”-您使用了 .env 来保证连接密码的安全......所以可能只需将连接 URI 添加到 .env 文件中,您就是好走吗?

    如果您的连接正常,那么我会查看您的服务器并建议测试是否使用标准路由解决了问题:

     app.route("/")
        .get(function(req, res) {
          res.sendFile(process.cwd() + "/views/index.html");
        })
    

    【讨论】:

    • 正在建立连接。我在 Heroku 上的 Config Vars 中添加了 MONGOBD_URI 作为键,并添加了 MongoDB Atlas 值。我会试试路由,看看会发生什么。
    • 你听起来像服务器路由......因为你所有的路由都在一个文件中(我通常将需要 MongoDB 的 API 路由分开),使用简单的 app.route 更容易,应该甜吗?
    猜你喜欢
    • 2020-07-27
    • 2021-01-19
    • 2021-12-25
    • 2016-08-05
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多