MongoDB net::ERR_CONNECTION_REFUSED on server - node.js

I am trying to make calls to my database from my react/node app hosted on a server. When run locally (using nodemon) the application is running at localhost:3000 and the server is hosted on port 4000, so I make api calls to localhost:4000. For example, localhost:4000/students displays the list of students stored in the MongoDB.
My server.js is as follows:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const PORT = 4000;
const cors = require('cors');
const mongoose = require('mongoose');
const studentRoute = require('./student.route');
const config = require('./secrets');
mongoose.Promise = global.Promise;
mongoose.connect(config.dbUri, { useNewUrlParser: true }).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
I am deploying my application to my site by uploading the build folder that results from npm run build to a folder called 'the-wall' (the name of the project). So to access the application I go to example.com/the-wall.
My mongoDB is hosted using MongoDB atlas, and have whitelisted my IP address and what I believe to be the IP address of the server. I am making calls using axios, with the following config:
const env = process.env.NODE_ENV;
export const app = axios.create({
baseURL:
env === 'production'
? 'https://example.com:4000/'
: 'http://localhost:4000/',
});
However, when I try to access example.com:4000/student I receive a net::ERR_CONNECTION_REFUSED error. As far as I can tell, mongoDB is not installed on the server. Is the URL I am using incorrect, or is there additional set up I need to do?
Note: I have also tried example.com/the-wall:4000/student, but I get a 404 error with this one.
Does the way I am trying to make a call to the database look correct? (i.e. is the URL correct with the port, etc)

Try to make it works locally with the production database.
If it works, it's an IP configuration problem on your server.
If it fails, it's a code configuration problem.

Related

How to build server.js express server around a remote github page JSON object

I have a GitHub page with one file in it: model.json. In model.json is a JSON object. I'd like to be able to access that object via a fetch request triggered in the frontend of my app.
However, I have only done mock localhost express server.jses thus far, and I don't know how to point the server.js file at a remote server.
That is, typically what I have done is something like this:
const express = require("express");
const bodyParser = require("body-parser");
const CORS = require("cors");
const app = express();
app.use(bodyParser.json());
app.use(CORS());
let modelObj = modelJSON;
// ^this "modelJSON" would be the json object in question,
// whether accessed remotely or locally.
app.get("/model.json", (req, res) => {
res.send(modelObj);
});
app.listen(5000, () => {
console.log("Server listening on port 5000");
});
I'm wondering how to make this listen to my https://<my-github-username>.github.io page instead of port 5000.
(Incidentally, will I want this server.js file in my local project/app file or in the github page root directory?)

Getting 404 error while fetching data from Mongo DB using Express/Node.js

I'm having trouble figuring our this 404 error I'm receiving. This is my first time trying to use Mongo DB and Node.js so forgive me, not used to routing yet. I'm simply trying to make a GET request to localhost:3000/users and render basic text to the page that says "users" so I can test the routes. I have not made any models or schema of any sort yet. I'm getting a message with the following when I get to the page: Cannot GET /users.
I believe I have my app.js file set up correctly and the app is connected to Mongo DB.
here's my app.js file - the route is at the bottom:
const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')
// Instantiate Morgan - this logs requests to the terminal (similar to rails)
const morgan = require('morgan')
// Load config.env file
dotenv.config({ path: './config/config.env' })
// initialize app with express
const app = express()
// run Connect DB to connect to your host
connectDB()
// if environment = development, run request logs
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'))
}
// We may deploy to heroku - so we need to set the env variable
const PORT = process.env.PORT || 5000
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`))
// Routes
app.use('/users', require('./routes/users'))
And here is my users.js file in my routes folder:
const express = require('express')
const router = express.Router()
// Routes
// #route GET /users -> gets all users in the database
router.get('/users', (req, response) => {
response.send('Users')
})
module.exports = router
And for good measure - here's my config.env file. I'm hosting on an AWS server via Mongo DB.
PORT = 3000
MONGO_URI = mongodb+srv://Ricky:<redacted>#readr.s99uq.mongodb.net/readr?retryWrites=true&w=majority
Any ideas on where I could be going wrong here? I believe I have set the route up properly but may have messed up somewhere.
Try localhost:3000/users/users because /users points to all routes in your users.js file and in that u have /users so it is nested. so if u want result in localhost:3000/users in your users.js file change route to / instead of /users
PS/ Also if thats your real username and password in config file remove that.

Facing issues in loading mongo database and frontend app

I'm working on creating an anonymous discussion forum where I've deployed my MongoDB on MongoDB Atlas (cloud platform) using Heroku. The whole app is developed using React. Here is my code for server.js:
var express = require('express');
const path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var models = require('./api/models/message');
var routes = require('./api/routes/routes');
var port = process.env.PORT || 3001;
var app = express();
var Message = mongoose.model('Message')
// Uncomment this line to run it on development mode (localhost) -- discussion is our db name //
// mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/discussion');
// This line is working on production mode //
mongoose.connect(process.env.MONGODB_URI || 'mongodb+srv://xxx:xxx#cluster0-xucmg.mongodb.net/test?retryWrites=true&w=majority');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
routes(app);
if (process.env.NODE_ENV === "production") {
app.use(express.static("frontend/build"));
console.log("production");
}
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'frontend/build', 'index.html'))
});
app.listen(port);
console.log('Server running on port ' + port);
My database name is discussion. When this line is uncommented:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/discussion');
The database loads fine and frontend code also works fine on localhost.
But I'm trying to host my database on the cloud (to resolve issues with Heroku build) with this line:
mongoose.connect(process.env.MONGODB_URI || 'mongodb+srv://xxx:xxx#cluster0-xucmg.mongodb.net/test?retryWrites=true&w=majority');
I'm not sure why because of this line the frontend part is not being loaded (on Heroku deployment link). I assume maybe this is because of database not being loaded. But, it'll be a great help if anyone can help me figure out this issue. I tried to follow this solution: Connecting Heroku App to Atlas MongoDB Cloud service by providing whitelist access but the issue still persist.
I fixed this issue by updating the mongoose dependency version >= 5.0.0
Even after adding CIDR as 0.0.0.0/0 in IP whitelist in MongoDB Atlas, updating mongoose version will help to overcome this type of issue.

Unable to load data from MongoDB Atlas from heroku app after succesful deployment

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
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.

How to resolve Chrome cookies resulting in nodejs ERR_CONNECTION_RESET when I have to store cookies olve

Currently making a MERN app, so I am using Node. I have the user's information stored in localstorage so when they refresh the page they are still logged in. Problem is, if I were to make any api calls to my backend it will result in a net::ERR_CONNECTION_RESET. And it is also weird that the error message will look something like: GET http://localhost:3000/api/roadmap/getAllRoadmapsButThumbnails net::ERR_CONNECTION_RESET, when localhost:5000 is my backend port but it is showing 3000, my client port.
My api calls perfectly fine when the user is logged out & thus there is nothing in the localstorage.
Has anyone encountered similar problems and have any insights?
What I have tried:
Changing proxy from just "http://localhost:5000" to
"proxy": {
"secure": true,
"target": {
"host": "https://localhost",
"port": 5000
}
},
Using full path in axios requests, this resulted in a CORS error, and I didn't proceed to make the CORS thing work because using the full path might cause weird stuff when website is deployed, and fixing the proxy routing seemed like a priority
More of my code
server.js:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const multer = require("multer");
const path = require("path");
const passport = require("passport");
const users = require("./routes/api/users");
const roadmap = require("./routes/api/roadmap");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/roadmap", roadmap);
app.use("/api/users", users);
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
Everything is http right now, I didn't get errors like this in my last website which also utilized jwt stored in localstorage, that was about 5 months ago.
EDIT
new things I tried:
Configuring the proxy manually
Starting chrome without certificate
Solution for my case: Use fetch instead of axios. I didn't post any client code but I used to fetch the data with:
axios.get("/api/roadmap/getAllRoadmapsThumbnails")
now, simply do:
fetch("/api/roadmap/getAllRoadmapsButThumbnails", { method: "GET" })
Why does it work. I have no idea, maybe if I put a few headers in axios axios would function properly as well. Still there is something weird, in console you can see the fetch log (you might have to check the "Log XMLHttpRequests" checkbox in console), and it shows:
Fetch finished loading: GET "http://localhost:3000/api/roadmap/getAllRoadmapsButThumbnails".
While my backend is 5000 and so it should be localhost:5000/api/...
If you are new to this problem, and getting problems ranging from ERR_CONNECTION_RESET to FAILED_TO_LOAD_RESOURCES to other ERRs,
Try these:
try using fetch. And best to define headers like {method: "POST", headers: {"Content-Type" : "application/json"}
turn off chrome extensions (use incognito will automatically disable extensions)
for a CORS error download npm install cors and then do app.use(cors()) in your server.js, according to this: https://github.com/axios/axios/issues/1414
Manually set up proxy & starting chrome ignoring certificate

Resources