This is what I am using. io.on() was working fine but after using mongoose.connect(), it's not working anymore. In terminal only showing
server is running:5000 mongo db connection null
Not sure why io.on() is not working.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const mongoose = require('mongoose');
const dbUrl = '' //removed db url for security reason.
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended":false}));
let message = []
app.get('/messages',(req,res)=>{
res.send(message)
})
app.post('/messages',(req,res)=>{
message.push(req.body)
io.emit('message',req.body)
res.sendStatus(200);
})
mongoose.connect(dbUrl, { useNewUrlParser: true }, (err) => {
console.log('mongo db connection', err)
})
io.on('connect',(socket)=>{
console.log("user connected")
})
const server = http.listen(5000,(err)=>{
if(err){
console.error();
}
console.log("server is running:"+ server.address().port);
});
this is my index.js file it's work for me
Related
Need help, I am trying to learn nodejs from youtube. I have created below but not getting any response from browser. Can you please check below code and advise what I have missed??
if I removed the courseModel.find ... from course.js and just write resp.send("XYZ") its showing on browser otherwise nothing is showing. please help
seems something is missing in mangodb connection string
--index.js
const connection = require('./model/connection');
const express = require('express');
const app = express();
const handleBars = require('express-handlebars');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path');
const courseController = require('./controllers/course');
const server = http.createServer(app);
app.use(bodyParser.urlencoded({
extended: true,
}))
app.use("/course", courseController);
server.listen(3900, () => {
console.log("server is in running mode.");
});
--connection.js
const mongoose = require('mongoose');
var conn = mongoose.createConnection("mongodb://localhost:27017/learning", (err) => {
if (!err) {
console.log("Mongo db connected");
} else {
console.log(err);
}
});
const courseModels = require("./course.model");
--course.model.js
const mongoose = require('mongoose');
var CourseSchema = new mongoose.Schema({
courseName: {
type: String,
required: 'Required'
},
courseId: {
type: String,
},
courseDuration: {
type: String,
}
});
module.exports = mongoose.model("Course", CourseSchema);
--course.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const courseModel = mongoose.model("Course");
router.get("/lists", (req, resp) => {
courseModel.find((err,docs)=>{
if(!err){
resp.send(docs)
}
});
});
module.exports = router;
--logs
issue resolved after updating the connection.js as below
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learning',
{
useNewUrlParser: true,
// useFindAndModify: false,
useUnifiedTopology: true
}, console.log("mongo db connected")
);
Insted of .
server.listen(3900, () => {
console.log("server is in running mode.");
});
use :
app.listen(3900, () => {
console.log("server is in running mode.");
});
I want to write a real-time chat application with socket.io and because my server and app file are separate, I kind of have no clue that how should I structure it to use socket.io instance in other parts of my app.
This is my app.js file.
const express = require("express");
const pug = require("pug");
const app = express();
module.exports = app;
and this is my server.js file
const app = require("./app");
const mongoose = require("mongoose");
mongoose
.connect(`mongodb://localhost:27017/${process.env.DATABASE}`)
.then(() => {
app.listen(process.env.PORT);
})
.catch((err) => {
console.error(`connection failed: ${err}`);
});
what is the best way to create an instance of socket.io and start it's connection for use in other parts of app?
You can use http with express app and then connect sockets through that http connection and you can listen and emit the topics inside the io.on('connection')
const app = require("./app");
const mongoose = require("mongoose");
const http = require('http').Server(app);
const io = require('socket.io')(http);
mongoose
.connect(`mongodb://localhost:27017/${process.env.DATABASE}`)
.then(() => {
app.listen(process.env.PORT);
io.on('connection', socket => {
console.log('socket connected',socket);
});
})
.catch((err) => {
console.error(`connection failed: ${err}`);
});
I will prefer this second way:
App.js
const express = require("express");
const pug = require("pug");
const app = express();
module.exports = app;
Server.js
const app = require("./app");
const realtime = require("./realtime");
const mongoose = require("mongoose");
const server = require("http").Server(app);
mongoose
.connect(`mongodb://localhost:27017/${process.env.DATABASE}`)
.then(() => {
app.listen(process.env.PORT);
require("./realtime.js")(server);
})
.catch((err) => {
console.error(`connection failed: ${err}`);
});
Realtime.js
module.exports = (app) => {
const io = require("socket.io")(app);
io.on("connection", (socket) => {
console.log("Socket connected")
})
};
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.
I am using Node.js with Express.js and for realtime data I am using socket.io.
I am trying to create on booking app.
So when the user will request through REST api the server will store the information to mongoDB via mongoose and after that the same data will be send to other users.
I am using router for different paths. below is my server.js
var express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const routes = require('./routes/routes');
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors())
app.use(express.urlencoded({ extended: false }));
app.set('socketio', io);
app.use(routes);
mongoose.Promise = global.Promise;
mongoose.connect(
'mongodb://localhost:27017/myapp',
{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }
).then(() => {
console.log('db connected');
}).catch(err => {
console.log(err,"hello 1998");
});
server.listen(8080);
And below is my route
const { Router } = require('express');
var router = Router();
const { main } = require('../helper/db_main')
const { checkAuthentication } = require('../helper/auth')
router.use('/api/v1/services',main,checkAuthentication,require('../controllers/services'));
router.use('/api/v1/category',main,checkAuthentication,require('../controllers/category'));
router.use('/api/v1/socket',main,checkAuthentication,require('../controllers/socket'));
module.exports = router;
and below is the place where I am trying to send/emit data to specific user but it is not working on client side i.e not able to see emit message on front-end side.
const list_all_category = (req,res) => {
console.log("Hjdnckjsdck")
var io = req.app.get('socketio');
// global.io.to("notify_me").emit("message", "hello ftomr");
let result_data
category.list_all_category().then(save_res => {
if (save_res)
result_data = res.status(200).send(save_res)
else{
result = 'fail'
res.send()
}
})
console.log("Here is ninja",io.id)
io.on('connection', function(socket){
console.log(socket.id); // same respective alphanumeric id...
})
io.sockets.on('connect', function(socket) {
const sessionID = socket.id;
})
io.on('notify',function(){
console.log("Galgotia")
})
io.sockets.emit('chat_message', 'world');
}
make use of this
socket.broadcast.to('ID').emit( 'send msg', {somedata : somedata_server} );
you can het each socket id for a specific user by using ${Socket.id}
If you are emitting anything always send the socket.id of a user to the client and send them back to the server.
I am trying to post data from POSTMAN to an external database that I created on mLab but I am getting the error db.collection is not a function.
There is a similar question thread but the answer is incomplete and doesn't save any keys/values I put into postman to mLab. The code that I am trying to make work is from this tutorial: https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2
My Code:
Server.js
const express = require('express'); // Load routes application
const MongoClient = require('mongodb').MongoClient; //Load database connection application
const db = require('./config/db');
const app = express(); // Assign express app a variable
const port = 8000; //Set local port value for server
const bodyParser = require('body-parser'); // **This has to come BEFORE routes
var assert = require('assert'); // ?
var databaseURL ='mongodb://external:api#ds123312.mlab.com:23312/soundfactory';
app.listen(port, () => {
console.log('')
console.log('We are live on ' + port);
console.log('')
});
MongoClient.connect(databaseURL, function(err, db) {
assert.equal(null, err);
console.log("API has succesfully connected to Sound Facotry mlab external database.");
console.log('')
db.close();
});
app.use(bodyParser.urlencoded({ extended: true }))
require('./app/routes')(app, {}); //Must come AFTER express w/ body parser
db.js
module.exports = {
url : 'mongodb://external:api#ds123312.mlab.com:23312/soundfactory'
};
index.js
const noteroutes = require('./note_routes');
module.exports = function(app,db)
{
noteroutes(app,db);
};
note_routes.js
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': 'An error has occurred' });
} else {
res.send(result.ops[0]);
}
});
});
};
partially correct code
server.js (code that partially works & doesn't throw the db.collections error like my original server.js file )
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({extened:true}));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err)
//require('./app/routes')(app,{});
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
})
Remove the node_modules folder and change mongodb version of your package.json
"mongodb": "^2.2.33"
and run below code :
npm install
change to this require('mongodb').MongoClient;