I have problem with getting data in my MERN app deployed on Heroku. Deployed app works fine locally – both app and MongoDB – but only locally. When I try to open web on other comp I got data error:
Failed to load resource: net:: ERR_Connection_Refused
localhost:8000/api/ads:1
I’ve read many threads about that problem. I think I’ve missed something. If you have any idea what I should do I’d be very glad for info.
Here is what I did:
- I’ve set general network access on 0.0.0.0/0 (MONGODB Atlas)
- I’ve set config vars on heroku
Here is my code:
server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const session = require('express-session');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo');
const bcrypt = require('bcryptjs');
// set dotenv
dotenv.config();
// import routes
const noticesRoutes = require('./routes/notices.routes');
const authRoutes = require('./routes/auth.routes');
const app = express();
/* MIDDLEWARE */
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
secret: bcrypt.hashSync('pass', 8),
store: MongoStore.create({ mongoUrl: process.env.DB_URL, collection: 'sessions' }),
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV == 'production',
},
}))
// access to storage folder
app.use(express.static(path.join(__dirname, '/client/build')));
app.use(express.static(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, '/uploads/')));
// use routes
app.use('/api', noticesRoutes);
app.use('/auth', authRoutes);
// error status
app.use((req, res) => {
res.status(404).send('404 not found...');
})
// React website
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
/* MONGOOSE */
const NODE_ENV = process.env.NODE_ENV;
let dbUri = '';
const password = process.env.PASSDB;
if(NODE_ENV === 'production') dbUri = 'mongodb+srv://MarcinEden:' + password + '@cluster1.sg1w6lh.mongodb.net/RealEstateBoard?retryWrites=true&w=majority';
else dbUri = 'mongodb+srv://MarcinEden:' + password + '@cluster1.sg1w6lh.mongodb.net/RealEstateBoard?retryWrites=true&w=majority';
mongoose.connect(dbUri, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.once('open', () => {
console.log('Successfully connected to the database');
});
db.on('error', err => console.log('Error: ' + err));
/* START SERVER */
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log('Server is running on port: '+ port);
});
Env vars
env.file
NODE_ENV = production
DB_URL = mongodb+srv://MarcinEden:[email protected]/RealEstateBoard?retryWrites=true&w=majority
If you need any more data, please let me know.