Postman: Connect ECONNREFUSED 127.0.0.1:5005 - node.js

I have developed an API endpoint. It was working fine before. Unfortunately the project folder got corrupted (I recreated the files db.js and server.js). But now when I try to fetch data from API, I'm getting:
"connect ECONNREFUSED 127.0.0.1:5005"
The URL I'm using is localhost:
And my server is running on the same port i.e. 5005:
Can someone please elaborate what can be the problem? My hunch is that when I recreated the files I may have missed something:
db.js:
const mongoose = require('mongoose');
const userName = "myUsername"
const password = "myPassword"
const dbName = "comfyRooms"
const dbURL = `mongodb+srv://${userName}:${password}#mongo-cluster.damzf.mongodb.net/${dbName}?authSource=admin&replicaSet=atlas-s7z01e-shard-0&readPreference=primary&appname=MongoDB%20Compass&ssl=true`
mongoose.connect(dbURL, {useUnifiedTopology: true, useNewUrlParser: true})
let connection = mongoose.connection
connection.on('error', () => {
console.log('Unable to connect to MongoDB')
})
connection.on('connected', () => {
console.log("MongoDB connection established :)")
})
module.exports = mongoose
server.js
const express = require('express')
const app = express()
const dbConfig = require('./db')
const roomsRoute = require('./routes/roomsRoute')
app.use('/api/rooms', roomsRoute)
const port = process.env.PORT || 5005
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
roomsRoute.js:
const express = require('express');
const router = express.Router();
const Room = require('../models/rooms');
router.get('/getallrooms', async (req, res) => {
try {
const rooms = await Room.find({});
return res.send(rooms);
} catch (error) {
return res.status(400).json({message: error});
}
});
module.exports = router;
I have attached the important files. Please let me know if any other information is missing. Thanks!

You are not passing the port variable to the listen function, you are just logging it
app.listen(() => {
console.log("Node JS server listening on port " + port)
})
This should work
app.listen(port, () => {
console.log("Node JS server listening on port " + port)
})

Related

how to use make express endpoints listen to same server as mongoose (apollo server)

i currently have an apollo server interacting with my mongodb database running on a port (localhost or the port given from the host when deployed). i also have another file (app.js) for web scraping that has routes and uses express, running on a different port.
i want the app.js express logic to run on the same port as the call
server.listen({ port: port}) in index.js. how do i do this, please? essentially something like putting the app.get calls in the mongoose.connect which does not seem possible, but so you can get the idea.
moving all the logic in app.js to index.js so the server listens to mongoose, apollo, and all the express endpoints i have in one place on the same, single port.
//index.js
const { ApolloServer } = require('apollo-server');
const mongoose = require('mongoose');
const express = require("express");
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
let port = process.env.port || 5000;
const typeDefs = require('./graphql/typeDefs');
const resolvers = require('./graphql/resolvers');
const { MONGODB } = require('./config.js');
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({ req })
});
mongoose.connect(MONGODB, { useNewUrlParser: true })
.then(() => {
console.log("MongoDB connected");
return server.listen({ port: port})
})
.then((res) => {
console.log(`Server running at ${res.url}`);
})
app.js (snippet) used for endpoints that return web scraping data
const express = require("express");
const cors = require('cors')
const cheerio = require('cheerio');
const axios = require('axios');
const app = express();
const port = 5001;
app.get("/events/", function(req, res) {
// redacted logic
let { zipCode } = req.query;
// Create a new yelpAPI object with your API key
let apiKey =[redacted];
let yelp = new yelpAPI(apiKey);
// Set any parameters, if applicable (see API documentation for allowed params)
let params = [{ location: zipCode }];
// Call the endpoint
yelp.query('events', params)
.then(data => {
// Success
res.send(data);
})
.catch(err => {
// Failure
console.log(err);
});
});
app.listen(port, () => console.log(`CORS-enabled web server listening on port ${port}!`));

MongoParseError: mongodb+srv URI cannot have port number

i have the following code
database.js file
const mongoose = require('mongoose');
const { MONGO_URI } = process.env;
exports.connect = () => {
// lets connect our database
mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
}).then(() =>{
console.log('connected to the database')
}).catch((error) =>{
console.log('connection to the database failed');
console.error(error);
process.exit(1);
});
};
index.js file
const http = require('http');
const app = require('./app');
const server = http.createServer(app);
const { API_PORT } = process.env;
const port = process.env.PORT || API_PORT;
server.listen(port, () => {
console.log(`server is running on port ${port}`)
})
when i run my index.js file i get an error
server is running on port 4001
connection to the database failed
MongoParseError: mongodb+srv URI cannot have port number
My .env file (note:password and name is made up)
API_PORT=4001
MONGO_URI=mongodb+srv://dwin:#12345#cluster0.3qohzms.mongodb.net/?retryWrites=true&w=majority
what coulb be wrong with the above code?

How to resolve server error in Socket.io?

I am creating a web application, using socket.io . A Server error occurred while connecting to the server. We found out that the error is in the backend. What could be written incorrectly here? Code:
const path = require('path');
const express = require('express');
const app = express();
const fs = require("fs");
var privateKey = fs.readFileSync('path').toString();
var certificate = fs.readFileSync('path').toString();
const http = require('https').Server({key:privateKey,cert:certificate}, app);
const io = require('socket.io')(http);
const port = 9998;
const debug = true;
var connectedArray = new Array()
const delay = 60 * 1000
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost',
user: 'user_name',
password: 'user_password',
database: 'database',
});
io.on('connection', (socket) => {
socket.on('register', msg => {
console.log("User registered")
connectedArray.push({
connectmessage: msg,
socket: socket,
})
})
socket.on('disconnect', () => {
if (debug) console.log('User disconnected')
})
})
app.use(express.static(path.resolve(__dirname, 'static')))
app.get('/', (req, res) => {
res.sendFile('./index.html')
})
http.listen(port, () => {
console.log(`Server started listening on port ${port}...`)
})
P.S: The problem began to arise after binding the domain
P.S 2: I have two sites on server, on different Apache virtual hosts
P.S 3: I am using https

ExpressJS: localhost didn’t send any data

I am writing an app, when I start the server, its working nicely, its connecting to database. But when I start http://localhost:5000 from the browser, it does not respond for a minuite then the browser shows a message:
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
Here is my app.js:
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
app.use(cookieParser);
app.use(express.json());
//const userRouter = require('./routes/user');
//app.use('/user', userRouter);
const startApp = async () => {
try {
await mongoose.connect('mongodb+srv://username:pass#cluster0-dcytp.mongodb.net/test?retryWrites=true&w=majority',
{ useUnifiedTopology: true,useNewUrlParser: true });
console.log(`successfully connected to database`);
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server runnin at ${port}`);
});
} catch (error) {
console.log(error.message)
}
}
startApp();
app.get('/', (req, res) => {
console.log("I am in the root");
res.send("hello World");
})
Why server is not responding from the browser?
try
app.use(cookieParser())
instead of
app.use(cookieParser)
Reference
I had the same problem db is connected but not able to send data. it looks weird but it works for me.
Add a new database user with new password, use the new userName and passw to connect your mongoodb
this is the exact like to add new database user
here is my db connection may it helps you too
mongoose.connect(DATABASE_URL, { useNewUrlParser: true,useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('connected to database'))
app.use(express.json())

Cannot connect to MongoDB via env variable

I am trying to conceal my connection string, so I installed env2 in my project. Then I made a config.env file that keeps my connection string like this:
export DB_URL='mongodb://user:userPassword#ds241968.mlab.com:41968/heroku_hc9xjmcl'
However when I use that variable as a connection string I cannot connect to Mlab I get the following error:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [ds241968.mlab.com:41968] on first connect [MongoError: Authentication failed.]
But when I try to connect only with the string without using env2 I connect perfectly, so why does the ahuthentication fail when I use a env variable and how can I connect with one properly? Here is my server.js:
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3009;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
const env = require('env2')('../config.env');
console.log(process.env.DB_URL)
app.use(cors());
app.use(bodyParser.json());
const { DB_URL } = process.env;
mongoose.connect( DB_URL , { useNewUrlParser: true } )
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Connection to MongoDB established succesfully!');
});
// Serve static assets
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
itemRoutes.route('/').get( async (req, res) => {
let collection = connection.collection("posts");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/comments').get( async (req, res) => {
let collection = connection.collection("comments");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/userComments')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
let comment = new Comment(req.body);
comment.save()
.then(comment => {
res.status(200).json({comment})
})
.catch(err => {
res.status(400).send('failed')
})
});
app.use('/', itemRoutes);
app.use('/userComments', itemRoutes);
app.listen(PORT, function() {
console.log('Server is running on' + ' ' + PORT);
})
Looks like you are using Node and Heroku. In that case,
You should set Heroku Config Vars (you can do this either via CLI or your Heroku Dashboard)
Refer to the config var in your node application the same way you are referring to now.
Remove 'env2' related code as you won't need it for this purpose
For example, if you create Heroku config var called "MONGO_URI", refer to it as process.env.MONGO_URI in your node application.
Details can be found here: https://devcenter.heroku.com/articles/config-vars#managing-config-vars

Resources