skip to Main Content

I have been trying to deploy a server for my first MERN app for the past week but I can’t seem to get it work. It works perfectly when I host it locally but I can’t seem to get the heroku server to work it usually crashes with error H10.

index(index.js)

import express from "express";
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
import dotenv from 'dotenv';

const app = express();
dotenv.config();

app.use(bodyParser.json({ limit: "30mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use('/posts', postRoutes);
app.get('/', (req,res) => {
    res.send('Expense Tracker API working')
} )

mongoose.connect(process.env.CONNECTION_URL || "mongodb+srv://expensetracker:[email protected]/?retryWrites=true&w=majority");

mongoose.connection.on('connected', () => {
    console.log("Server is connected with Mongoose!");
});

app.listen(process.env.PORT || 5000, () => {
    console.log('Server is running on port')
});

package.json

{
  "name": "server",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "express": "^4.18.1",
    "mongoose": "^6.3.6",
    "nodemon": "^2.0.16"
  },
  "description": ""
}

Procfile

web: node index.js

Routes(routes/posts.js)

import express from "express";
import { getPosts, createPosts, updatePost, deletePost } from '../controllers/posts.js'

const router = express.Router();

router.get('/', getPosts);
router.post('/', createPosts);
router.patch('/:id', updatePost)
router.delete('/:id', deletePost);

export default router;

Controllers(controllers/posts.js)

import mongoose from "mongoose";
import PostMessage from "../models/postMessage.js";

export const getPosts = async (req, res) => {
    try {
        const postMessages = await PostMessage.find();

        res.status(200).json(postMessages);
    } catch (error) {
        res.status(401).json({ message: error.message });
    }
}

export const createPosts = async(req, res) => {
    const post = req.body;

    const newPost = new PostMessage(post);

    try {
        await newPost.save();
        res.status(201).json(newPost);

    } catch (error) {
        res.status(409).json({ message: error });
    }
}

export const updatePost = async(req, res) => {
    const { id: _id } = req.params
    const post = req.body;
    if(!mongoose.Types.ObjectId.isValid(_id)) return res.status(404).send("Unable to find post with that id");

    
    const updatedPost = await PostMessage.findByIdAndUpdate(_id, { ...post, _id}, { new: true} );
    res.json(updatedPost)
}

export const deletePost = async(req, res) => {
    const { id } = req.params
    if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send("Unable to find post with that id");    
    await PostMessage.findByIdAndRemove(id);
    res.json({ message: 'Post deleted sucess' })
}

2

Answers


  1. Chosen as BEST ANSWER

    I used this heroku resource to find the answer. I had to set my CONNECTION_URL on heroku and allow my mongodb to be accessed from anywhere.


  2. To solve this problem, we must done with file named Procfile with the following content: web: node ./app.js

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search