Giulio
Giulio

Reputation: 5

Node.js works locally but not once on Heroku

I am encountering this problem when I try to deploy my node.js app on heroku.

This is my app:

require("dotenv").config();
const cool = require("cool-ascii-faces");
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const _ = require("lodash");
const port = process.env.PORT || 3000;

const homeStartingContent =
  "I have created this website in order to allow you to create a web-blog. In order to do this I am using MongoDB to store all of your posts, Express to deal with the back-end server, and EJS to automatically create a template html page with the input from the user. Give it a try!";
const aboutContent =
  "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Non diam phasellus vestibulum lorem sed. Platea dictumst quisque sagittis purus sit. Egestas sed sed risus pretium quam vulputate dignissim suspendisse. Mauris in aliquam sem fringilla. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Amet massa vitae tortor condimentum lacinia quis vel eros. Enim ut tellus elementum sagittis vitae. Mauris ultrices eros in cursus turpis massa tincidunt dui.";
const contactContent =
  "Scelerisque eleifend donec pretium vulputate sapien. Rhoncus urna neque viverra justo nec ultrices. Arcu dui vivamus arcu felis bibendum. Consectetur adipiscing elit duis tristique. Risus viverra adipiscing at in tellus integer feugiat. Sapien nec sagittis aliquam malesuada bibendum arcu vitae. Consequat interdum varius sit amet mattis. Iaculis nunc sed augue lacus. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. Pulvinar elementum integer enim neque. Ultrices gravida dictum fusce ut placerat orci nulla. Mauris in aliquam sem fringilla ut morbi tincidunt. Tortor posuere ac ut consequat semper viverra nam libero.";
let posts = [];

const app = express();

app.set("view engine", "ejs");

app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);
app.use(express.static("public"));

mongoose.connect(process.env.USERLINK, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
});
mongoose.connection
  .once("open", function () {
    console.log("Connection has been made!");
  })
  .on("error", function (error) {
    console.log("Error is: ", error);
  });

const postSchema = new mongoose.Schema({
  title: String,
  body: String,
});

const Post = mongoose.model("Post", postSchema);

app.get("/", function (req, res) {
  Post.find({}, function (err, results) {
    res.render("home", {
      homeStartingContent: homeStartingContent,
      posts: results,
    });
  });
});

app.get("/about", function (req, res) {
  res.render("about", {
    aboutContent: aboutContent,
  });
});

app.get("/contact", function (req, res) {
  res.render("contact", {
    contactContent: contactContent,
  });
});

app.get("/compose", function (req, res) {
  res.render("compose");
});

app.get("/posts/:postId", function (req, res) {
  const id = req.params.postId;

  Post.findOne(
    {
      _id: id,
    },
    function (err, foundPost) {
      if (!err) {
        res.render("post", {
          postTitle: foundPost.title,
          postBody: foundPost.body,
        });
      } else {
        console.log(err);
      }
    }
  );
});

app.get("/cool", (req, res) => res.send(cool()));

app.post("/compose", function (req, res) {
  const post = new Post({
    title: req.body.postTitle,
    body: req.body.postBody,
  });
  post.save();
  res.redirect("/");
});

app.listen(port, () =>
  console.log(`Example app listening at http://localhost:${port}`)
);

The app works perfectly when I run it with node index.js or heroku local

Once I do heroku open I get this:

2020-10-16T09:39:10.000000+00:00 app[api]: Build succeeded
2020-10-16T09:39:10.556071+00:00 heroku[web.1]: Starting process with command `node index.js`
2020-10-16T09:39:13.612626+00:00 app[web.1]: Example app listening at http://localhost:44608
2020-10-16T09:39:13.614501+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
2020-10-16T09:39:13.614507+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:651:11)
2020-10-16T09:39:13.614508+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:342:10
2020-10-16T09:39:13.614509+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2020-10-16T09:39:13.614509+00:00 app[web.1]: at new Promise (<anonymous>)
2020-10-16T09:39:13.614510+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2020-10-16T09:39:13.614510+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:341:10)
2020-10-16T09:39:13.614510+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:29:10)
2020-10-16T09:39:13.614510+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1138:30)
2020-10-16T09:39:13.614511+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
2020-10-16T09:39:13.614511+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:986:32)
2020-10-16T09:39:13.614511+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:879:14)
2020-10-16T09:39:13.614512+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
2020-10-16T09:39:13.614512+00:00 app[web.1]: at internal/main/run_main_module.js:17:47
2020-10-16T09:39:13.614627+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
2020-10-16T09:39:13.614730+00:00 app[web.1]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2020-10-16T09:39:14.238165+00:00 heroku[web.1]: State changed from starting to up
2020-10-16T09:39:24.019647+00:00 heroku[router]: at=info method=GET path="/cool" host=blog-ejs.herokuapp.com request_id=66867e07-2f4d-4fbb-8807-9add195364f4 fwd="151.95.172.180" dyno=web.1 connect=0ms service=20ms status=200 bytes=225 protocol=https
2020-10-16T09:39:24.403126+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=blog-ejs.herokuapp.com request_id=3be02d5f-a995-4081-a11b-feec4221111a fwd="151.95.172.180" dyno=web.1 connect=0ms service=3ms status=404 bytes=394 protocol=https
2020-10-16T10:04:10.994361+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=blog-ejs.herokuapp.com request_id=f1106907-3674-4762-8bdb-5bba9492b68f fwd="151.95.172.180" dyno=web.1 connect=0ms service=30000ms status=503 bytes=0 protocol=https
2020-10-16T10:04:49.073814+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path="/" host=blog-ejs.herokuapp.com request_id=ef4db75b-7430-4b74-90d0-ebdffc6eb16b fwd="151.95.172.180" dyno=web.1 connect=1ms service=30000ms status=503 bytes=0 protocol=https

Any ideas?

Upvotes: 0

Views: 130

Answers (1)

Arpan Kc
Arpan Kc

Reputation: 938

In this line:

mongoose.connect(process.env.USERLINK, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
});

The first parameter comes from an environment variable (process.env.*) . So make sure the USERLINK environment variable is present in the Heroku environment. From what I can see from the logs, there is an issue with the first parameter being passed in (perhaps the environment variable is not present)

Upvotes: 2

Related Questions