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())
Related
I am trying to connect MongoDB with my signup.js, but it's not connecting. I am unable to find the problem. How can I solve this?
Code of signup.js:
const express = require('express')
const app = express()
require("./db/mydb");
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(4000, () => {
console.log(`App listening on port 4000`)
})
Code of mydb.js:
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mydata",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
}).then(()=>{
console.log("connection successful")
}).catch((e)=>{
console.log("Not connected")
})
Error:
App listening on port 4000
Not connected
If the last log statement is replaced with console.log(e), the output is:
MongoParseError: option usecreateindex is not supported
Here you have a simple example of how to connect MongoDB to Node.js using Express.js and Mongoose on localhost obviously:
File server.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Express and Mongoose connection!");
});
// Connect to db
mongoose
.connect("mongodb://localhost:27017/test")
.then(() => {
// Listen for requests
app.listen(port, () => {
console.log(
`Connected to DB & Server is listening at http://127.0.0.1:${port}`
);
});
})
.catch((error) => {
console.log(error);
});
And as we can read in the Mongoose documentation → no more deprecation warning options
useNewUrlParser, useUnifiedTopology, useFindAndModify, and
useCreateIndex are no longer supported options. Mongoose 6 always
behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex
are true, and useFindAndModify is false. Please remove these options
from your code.
It was tested with: "express": "^4.18.1", "mongoose": "^6.6.5"
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)
})
I created Express, Node, React app.
Now, i want to integrate socket.io to the app.
I searched all over the internet and i found that all the socket.io events are in the initial server.js/app.js file.
But, i want to separate the socket.io events from the main file and then import it to the main file, just like routes/controllers files.
My code right now:
var app = require("express")();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
const mongoose = require("mongoose");
const stocks = require("./routes/stockRoutes");
const bodyParser = require("body-parser");
const cors = require("cors");
const port = 5000;
app.use(stocks);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.set("socketio", io);
const uri =
"mongodb+srv://admin:admin1234#investockcluster0.jp2wh.mongodb.net/<stocks_data>?retryWrites=true&w=majority";
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB database connection established successfully");
});
io.on("connection", (socket) => {
socket.emit("hello", "world");
console.log("New Connection");
});
http.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
I want that this code will be in file like "socketEvents.js" and then require it.
io.on("connection", (socket) => {
socket.emit("hello", "world");
console.log("New Connection");
});
Thanks a lot :)
Just put your socket.io code in another module and pass in the server in an initialization method:
// in sock.js
module.exports = function(server) {
const io = require("socket.io")(server);
io.on("connection", (socket) => {
socket.emit("hello", "world");
console.log("New Connection");
});
// put other things that use io here
}
Then, in your main file:
require('./sock.js')(http);
FYI, http is a crummy variable name for your server. You really ought to name it server.
I am trying to create a chat app which, uses a real-time database with MongoDB and Websocket.
This is my first React, MongoDB, and Websocket Project, so please excuse possible trivialities. :D
I am currently working on creating a new user, refreshing the database, and finally displaying the created user in every user's frontend in real-time.
Creating and saving a new user works fine and also logging the new user's data in real-time after the database changed (via socket.io) is working as well. Now, I would like to access the information that the database changed in the frontend of my app, so I can refresh the unordered list of users. Now there is the problem I'd like to solve: I try to connect the frontend with my backend by using this code:
//...
import socketIOClient from "socket.io-client";
const ENDPOINT = "localhost:5000";
const MainContentArea = () => {
useEffect(()=>{
const socket = socketIOClient(ENDPOINT);
socket.on("changes", data => {
console.log(data);
})
});
//...
The following is my backend code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const index = require('./routes/index');
const port = process.env.PORT || 5000;
const app = express();
app.use(index);
const server = app.listen(port, () => {
console.log(`Server ist running on port: ${port}`);
})
const io = socketIo(server).listen(server);
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config({
path: './.env'
});
const Users = require('./models/user.model');
app.use(cors());
app.use(express.json());
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
},
function(err){
if(err){
console.log("server.js err line 44");
throw err;
}
io.on('connection', (socket) => {
console.log('user connected');
socket.on('disconnect', (socket) => {
console.log('user disconnected');
})
})
Users.watch().on('change', (change) => {
console.log('socket says: something changed in db');
console.log('change: ', change.fullDocument);
io.to(change.fullDocument).emit('changes',change.fullDocument)
})
}
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
I keep getting the Error message:
WebSocket connection to 'ws://localhost:5000/socket.io/? EIO=3&transport=websocket&sid=33wU6D8PnqclT3iZAAAB' failed: Error during WebSocket handshake: Unexpected response code: 400
I am using Chrome and I am working on MacOS.
I am very thankful for any suggestions that might help solve my problem.
I hope, how I posted my question is helpful for anybody who is willing to help me with this. If not, feel free to give me suggestions on what to do better next time! This is my first post here.
It shows no error at all. Even cosole shows the database is connected. But it is not showing the data. When I go to http://localhost:5000/tasks it shows
Cannot GET /tasks
what am I missing here?
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
require('dotenv').config()
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#cluster0.vwtzw.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
const port =5000;
app.get('/', (req, res) => {
res.send('hello world!');
});
const client = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true });
client.connect(err => {
const tasksCollection = client.db("VolunteerNetwork").collection("tasks");
app.get('/tasks',(req, res) => {
tasksCollection.find({})
.toArray( ( err, documents) => {
res.send(documents);
console.log(documents);
console.log('database connected');
})
})
});
app.listen(port);
after I run it shows -
undefined
database connected
mongo database name: VolunteerNetwork.tasks
the get route is inside the connect method - try reorganizing the code so that you open the connection when a request is made
const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb://localhost:27017`;
const client = new MongoClient(uri, { useNewUrlParser: true , useUnifiedTopology: true });
router.get('/tasks',(req, res) => {
client.connect(err => {
const tasksCollection = client.db("VolunteerNetwork").collection("tasks");
tasksCollection.find({})
.toArray( ( err, documents) => {
res.send(documents);
console.log('database connected');
console.log(documents);
})
})
});
The code works perfectly fine. It is an accurate approach.
My mistake was I did not give access to the username to edit/read the database in MongoDB. Giving the privilege made the work done.