Mern Exercise Tracker won't work on Heroku

Hi everyone my name is Michele and it’s the first time asking for help on this forum.

As per title I am trying to deploy the Exercise tracker on heroku but it’s not working.
I will attach some pictures of the code in the server file plus the log on heroku.

the structure of the files is 2 separate folder 1 client and the other backend.

The Error is not Found and from what I understand it doesn’t find the index html file but how?

the client side it’s been deployed on netlify and np on that side but the backend part on heroku it’s being a pain.

Server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

const path = require('path');

require('dotenv').config();

const app = express();


const PORT = process.env.PORT || 5000

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

const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser:true,useCreateIndex:true,useUnifiedTopology: true});

const connection = mongoose.connection;
connection.once('open',() => {
    console.log('Connection Enstablished')
})


const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);



if(process.env.NODE_ENV === "production") {
    app.use(express.static('Client/build'));

    app.get('*', (req,res)=>{
        res.sendFile(path.join(__dirname,'build','index.html'));
        
    } )
}



app.listen(PORT,() => {
    console.log('Server up and running')
})

json file

{
  "name": "backend",
  "version": "1.0.0",
  "main": "server.js",
  "scripts": {
    
    
    "start":"node server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.9.20"
  }
}

I hope someone can give me an help …

Welcome, Mike.

It is going to be difficult to help, without seeing your directory structure.

Just to clarify, this is where your problem is:

app.get('*', (req,res)=>{
        res.sendFile(path.join(__dirname,'build','index.html'));
    } )

It is completely likely you need only say: res.sendFile('index.html');

But, without knowing more, we will struggle to assist more.

Hope this helps

Hi Sky020, I changed to this res.sendFile('index.html'); and now I have a different error which is 500 internal server error, I will show you my directory structure plus in the log doesn’t seem to be any error.

Nothing you have shown suggests you have a build step or directory. If you are not building/packaging your files, you should be pointing to your main index.html file, likely in your src folder.

With Heroku, you need to be viewing your logs, the same time you are deploying your app. Otherwise, some logs are not recorded.

Hope this helps

I am sorry Sky020 but I don’t know what do you mean with

Blockquote you have a build step or directory. If you are not building/packaging your files, you should be pointing to your main index.html file, likely in your src folder.

if I try npm build in the backend folder it doesn’t work, i don’t know why, I can point my main index.html but it’s in the client folder how do I point there?

this above is one of the last log, and everything seems fine but still I have the internal error, also if I go on the website Exercise-traker the create use works and it’s connected to mongo but the create exercise does not.

You will need to provide your code in some way: GitHub, Glitch, Repl.it, CodeSandbox…

What I mean is, with a build, you will normally have a build script. This is located in your package.json file. You call it with npm run build, and it normally makes use of some other API like webpack to bundle your files into something you can deploy. So, considering your app is being built on Heroku, either Heroku is making use of your start script, or it has found a build script. But, the command node server.js is not a building command that bundles. So, Heroku is probably using your development files with the start script.

I cannot help further, without seeing your code. Getting something on GitHub, if you have not, would be (in my opinion) one of the best things for you to do as a developer.

Hope this helps

I have github yes, i created a pull request where I put the backend files with the client files all together,cause on my master I have just the client side, the backend is on a repo that is pushed on heroku master so I don’t know how to get that so I know that it’s a mix now but at least you can see the files.
the package.json and the packagelock.json are backend if you want the client side they are in the master branch.Repo

Ok after days of looking to solve my problem, this morning I finally found the solution.

I will post my solution just in case someone else encounter the same issue.

All the issue that I was having with the backend ( cannot get/, not found, internal server error etc…) was because I was trying to deploy on heroku the client side that was already deployed on Netlify.
I was using this

if(process.env.NODE_ENV === "production") {
    app.use(express.static('Client/build'));

    app.get('*', (req,res)=>{
        res.sendFile(path.join(__dirname,'build','index.html'));
        
    } )
}

When I actually did not need it at all, because my app was not entirely on heroku, heroku was just for my server side, so what i did was this

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

const http = require('http');
const router = express.Router();



require('dotenv').config();

const app = express();

const server = http.createServer(app);

const PORT = process.env.PORT || 5000

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

const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser:true,useCreateIndex:true,useUnifiedTopology: true});

const connection = mongoose.connection;
connection.once('open',() => {
    console.log('Connection Enstablished')
})


const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');

app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);

router.get('/',(req,res)=> {
    res.send('server is up and running')
} )


//if(process.env.NODE_ENV === "production") {
//    app.use(express.static('Client/build'));

  //  app.get('*', (req,res)=>{
   //     res.sendFile('index.html', { root:'Client/public' });
       
   // } )
//}

app.use(router)

server.listen(PORT,() => {
    console.log('Server up and running on')
})

I called the http module, and the router module, I create the server and I create a default route for the server just using the

res.send()

and not

res.sendFile()

because I didn’t need to send any file that where my mistake was ahahahah.

In the tutorial it doesn’t say how to deploy so you don’t have the default route created and when you look on google obviously solution are this

res.sendFile()

which was not correct in my case but if you are deploying the entire app on heroku I guess you will need that.

Once I solved this issue, I found out that I had another issue but in the client side, the app was working but not entirely, The user create was working but not the exercise create and the problem was because In the tutorial the instructor use

window.location(’/’)

in the onSubmit function to go back to the first page, but in my case and I think is a generic problem once you hit create exercise, the window.location run and it is so fast that the onSubmit function doesn’t talk with the server and database and do not create the object and obviously there will be nothing to display ahahahah, I found out all these cause I has looking in the heroku logs and the connection time was 0ms so there was no connection at all, anyway I deleted the

window.location(’/’)

and after the post request I set the default state just to empty the inputs.

 this.setState({
            username: "",
            description:"",
            duration:0,
            date:new Date(),
            
        })

I hope this will help people that get stacked like me, but the good thing is that getting stacked is helpful to learn a lot of stuff :wink:

thank you Sky020 for your patience trying to solve my issue :slight_smile: