Search code examples
mongodbherokumernmongodb-atlashttp-status-code-405

Heroku not connecting to MongoDB Atlas - Error 405 not allowed


I realize this question or similar has been asked 20 times and I've read through all of the entries and tried the fixes with no luck.

I am getting a 405 error when trying a POST request from the DB only when using heroku.

My code works when deploying from my own local server both from src and build folders. I have tried the following:

  • update Atlas whitelist to 0.0.0/0
  • created an ENV key in Heroku and set up code to use that.
  • reset my db password on atlas
  • added cors module to Express code.

I'm completely at a loss as to why this isn't working now.

Here's the code in question with the first POST Request:

App.mjs

import "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import { fileURLToPath } from "url";
import path, { dirname } from "path";
import bodyParser from "body-parser";
import { randomProfileImage } from "./randomProfileImage.mjs";
import helmet from "helmet";
import cors from "cors";
import {
    createNewComment,
    createNewReply,
    allModels,
} from "./models/comments.mjs";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(path.join(__filename, "..", "..", "package.json"));

const app = express();

const localLinkToDB =
    "mongodb+srv://david:[email protected]/commentsDB?retryWrites=true&w=majority";

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(helmet());
app.use(cors());

mongoose
    .connect(process.env.DB_URI || localLinkToDB, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
    })
    .then((result) =>
        app.listen(process.env.PORT || 3000, () => {
            console.log(`server started on port 3000.`);
        })
    )
    .catch((err) => console.log(err));

if (process.env.NODE_ENV === "production") {
    app.use(express.static(`${__dirname}/build`));

    console.log("using static");
}

app.get("/ping", function (req, res) {
    return res.send("pong");
});


app.post("/", async (req, res, error) => {
    try {
        const modelName = allModels[req.body.dbToQuery];

        const result = await modelName.find({}).lean();
        result.forEach((comment) => (comment._id = comment._id.toString()));

        res.json(result);
    } catch {
        console.log(error);
    }
});

Request from the front end:

const loadAllMessagesInit = async () => {
        try {
            const response = await fetch("/", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    dbToQuery: "TestComment",
                }),
            });
            const allComments = await response.json();
            if (allComments) {
                allComments.forEach(
                    (comment) =>
                        (comment.date = generateDateString(new Date(comment.date)))
                );
                buildAllNestedObjects(allComments);
                setAllMessages(allComments);
            }
        } catch (err) {
            console.log(err);
        }
    };
    loadAllMessagesInit();
}, []);

Here is my package.json (I'm using the heroku build addon for create-react-App)

{
    "name": "comment-system",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@testing-library/jest-dom": "^4.2.4",
        "@testing-library/react": "^9.5.0",
        "@testing-library/user-event": "^7.2.1",
        "body-parser": "^1.19.0",
        "cors": "^2.8.5",
        "dotenv": "^8.2.0",
        "express": "^4.17.1",
        "helmet": "^3.23.3",
        "local-storage": "^2.0.0",
        "mongoose": "^5.9.21",
        "nodemon": "^2.0.4",
        "react": "^16.13.1",
        "react-dom": "^16.13.1",
        "react-scripts": "3.4.1"
    },
    "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
    },
    "eslintConfig": {
        "extends": "react-app"
    },
    "browserslist": {
        "production": [
            ">0.2%",
            "not dead",
            "not op_mini all"
        ],
        "development": [
            "last 1 chrome version",
            "last 1 firefox version",
            "last 1 safari version"
        ]
    },
    "proxy": "http://localhost:8080",
    "engines": {
        "node": "14.4.0"
    }
}

And finally here is the error log I'm gettting from heroku:

2020-07-17T00:55:35.355724+00:00 heroku[router]: at=info method=GET path="/" host=dhc-comment-system.herokuapp.com request_id=174acd8d-d05d-4036-8be7-46ba92388073 fwd="38.94.243.199" dyno=web.1 connect=1ms service=2ms status=304 bytes=168 protocol=https
2020-07-17T00:55:35.356334+00:00 app[web.1]: 10.11.254.71 - - [17/Jul/2020:00:55:35 +0000] "GET / HTTP/1.1" 304 0 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.464666+00:00 heroku[router]: at=info method=GET path="/static/css/main.55682b50.chunk.css" host=dhc-comment-system.herokuapp.com request_id=a95fb494-5760-46c6-ac62-c11ada41246e fwd="38.94.243.199" dyno=web.1 connect=1ms service=2ms status=304 bytes=168 protocol=https
2020-07-17T00:55:35.465422+00:00 app[web.1]: 10.11.254.71 - - [17/Jul/2020:00:55:35 +0000] "GET /static/css/main.55682b50.chunk.css HTTP/1.1" 304 0 "https://dhc-comment-system.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.527624+00:00 app[web.1]: 10.11.254.71 - - [17/Jul/2020:00:55:35 +0000] "GET /static/js/2.f296f9a5.chunk.js HTTP/1.1" 304 0 "https://dhc-comment-system.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.532492+00:00 heroku[router]: at=info method=GET path="/static/js/2.f296f9a5.chunk.js" host=dhc-comment-system.herokuapp.com request_id=7f3213fd-e1ce-427d-9b82-de406425ea72 fwd="38.94.243.199" dyno=web.1 connect=0ms service=2ms status=304 bytes=170 protocol=https
2020-07-17T00:55:35.590157+00:00 heroku[router]: at=info method=GET path="/static/js/main.cf3d813b.chunk.js" host=dhc-comment-system.herokuapp.com request_id=cf000b30-79b6-476f-9659-46119e4a1311 fwd="38.94.243.199" dyno=web.1 connect=0ms service=2ms status=304 bytes=169 protocol=https
2020-07-17T00:55:35.590291+00:00 app[web.1]: 10.43.233.181 - - [17/Jul/2020:00:55:35 +0000] "GET /static/js/main.cf3d813b.chunk.js HTTP/1.1" 304 0 "https://dhc-comment-system.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.625984+00:00 heroku[router]: at=info method=GET path="/static/css/main.55682b50.chunk.css.map" host=dhc-comment-system.herokuapp.com request_id=3dad5af5-355c-4471-8671-3b90712cb4b8 fwd="38.94.243.199" dyno=web.1 connect=0ms service=2ms status=304 bytes=169 protocol=https
2020-07-17T00:55:35.626571+00:00 app[web.1]: 10.11.254.71 - - [17/Jul/2020:00:55:35 +0000] "GET /static/css/main.55682b50.chunk.css.map HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.632069+00:00 heroku[router]: at=info method=GET path="/static/js/2.f296f9a5.chunk.js.map" host=dhc-comment-system.herokuapp.com request_id=fdcc6797-5151-4708-8752-90efb710812c fwd="38.94.243.199" dyno=web.1 connect=0ms service=3ms status=304 bytes=170 protocol=https
2020-07-17T00:55:35.632204+00:00 app[web.1]: 10.45.9.232 - - [17/Jul/2020:00:55:35 +0000] "GET /static/js/2.f296f9a5.chunk.js.map HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.696228+00:00 heroku[router]: at=info method=POST path="/" host=dhc-comment-system.herokuapp.com request_id=26b6dfce-3385-44f3-8273-c3659bd045d8 fwd="38.94.243.199" dyno=web.1 connect=0ms service=1ms status=405 bytes=728 protocol=https
2020-07-17T00:55:35.696326+00:00 app[web.1]: 10.45.9.232 - - [17/Jul/2020:00:55:35 +0000] "POST / HTTP/1.1" 405 568 "https://dhc-comment-system.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.697233+00:00 heroku[router]: at=info method=GET path="/static/js/main.cf3d813b.chunk.js.map" host=dhc-comment-system.herokuapp.com request_id=a079d11d-c093-40b2-8a89-38d0bd21490b fwd="38.94.243.199" dyno=web.1 connect=0ms service=2ms status=304 bytes=169 protocol=https
2020-07-17T00:55:35.697840+00:00 app[web.1]: 10.11.254.71 - - [17/Jul/2020:00:55:35 +0000] "GET /static/js/main.cf3d813b.chunk.js.map HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.977491+00:00 app[web.1]: 10.43.252.33 - - [17/Jul/2020:00:55:35 +0000] "GET /site.webmanifest HTTP/1.1" 304 0 "https://dhc-comment-system.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"
2020-07-17T00:55:35.981257+00:00 heroku[router]: at=info method=GET path="/site.webmanifest" host=dhc-comment-system.herokuapp.com request_id=17143eb6-c38b-480f-817a-7f9afc7e5144 fwd="38.94.243.199" dyno=web.1 connect=1ms service=2ms status=304 bytes=168 protocol=https

Solution

  • I figured out what my mistake was after some help from a rep at clever-cloud. It turns out all my routing was correct except for the fact that I had capitalized App.mjs in my package.json when the file was app.mjs. On my local host environment it didn't matter but on the linux based server(s) the case matters and so it couldn't connect correctly.

    It didn't have a clear error message, and my inexperience made it so I didn't understand my mistake. Many thanks to the support team at clever-cloud! I was able to get it working on clever-cloud, heroku, and a shared-server A2 hosting site.