Reputation: 27
I am a beginner to MERN stack development.I have deployed my nodejs app without any error on heroku.But the app does not load the data from mongodb atlas database.The app connects to database and displays the data without any problem when run locally.Any ideas on how to fix this?
I have already added environment variable on heroku and whitelisted all ip addressed on atlas.But still the app does not load data from the database
server.js
const express = require('express'); //nodejs framework for creating web apps
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config(); //for setting environment variables on server
const app = express(); //creating the app
//Serve static assets if in production
if(process.env.NODE_ENV ==='production'){
//Set static folder
app.use(express.static('client/build'));
app.get('*',(req, res) => {
res.sendFile(path.resolve(__dirname,'client','build','index.html'));
});
}
////////////////////////////////////////
const port = process.env.PORT || 5000;
app.use(cors()); //for cross origin resource sharing ie.cross domain requests
app.use(express.json()); //for handling json data
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{ useNewUrlParser: true, useCreateIndex: true ,useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('Database connection established successfully');
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
//executes the files in the second argument when user enters the url 'rooturl/firstargument'
app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);
app.listen(port,() => {
console.log(`Server is running on port:${port}`);
});
http://justworkout.herokuapp.com/ This is the app url The list of exercises should load from the database but nothing is loaded as you can see
Upvotes: 0
Views: 1112
Reputation: 711
I had the same problem. The solution for me it was to go to my client folder and change all my fetch methods. For fetching data I'm using axios. I was sending request to localhost:5000 and then /api/etc. The request was something like this:
axios.get("http://localhost:5000/apps/blog").then()
To make it work on heroku I needed to remove the prefix of localhost and leave just the api path.
axios.get("/apps/blog").then()
Changing this sort my problem.
Upvotes: 2