In my express's route I do this
var cookie = require('cookie');
var server = require("http").Server(express);
var io = require("socket.io")(server);
server.listen(5000);
io.on('connection', function(client) {
console.log('socket connected') // returned socket connected
if(client.request.headers.cookie){
console.log(userId) //returned userId
var userId = cookie.parse(client.request.headers.cookie).userId;
client.on('call_'+userId, function(data) {
io.emit('call_'+userId,data);
});
}
});
router.use(function(req, res, next){
if(!req.user){
res.redirect('/login');
}else{
res.locals.username = req.user.username;
//set cookie for socket.io purposes
if(!cookie.parse(req.headers.cookie).userId){
res.cookie('userId',querystring.escape(req.user._id));
}
return next();
}
});
router.get('/', function(req, res, next) {
res.redirect('./dashboard');
});
and I try to do an emit to port 5000, it worked. But it only work after I refresh the page after login, it doesn't work when I first come to dashboard's page. I've tried to see if the socket is connected upon login, and I did see it's connected.
Why it only for after I refresh? What's the issue?
Related
I am learning nodejs and I want to check if user is logged in by checking session.login value but when session.login is created and then user is redirected to main page, session.login is again undefined.
emit 'logged' is just redirecting user to the dashboard but dashboard checks if session.login exists, it shows undefined and user is redirected again to the login page.
var app = require('express')(); //load and initialize express
var http = require('http').Server(app); //create http server
var io = require('socket.io')(http); //add socket to http server
var path = require('path') //initialize path module
var port = 3000; //define port
var mysql = require('mysql'); //load mysql module
var session = require('express-session'); //sessions module
var login; //login
var md5 = require('md5');
//connecting to the database
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'chat'
});
con.connect((error) => {
if(error) console.log('Error with database connection.');
else console.log("Connected to the database!");
});
//define default path
app.use(require('express').static(path.join(__dirname, 'public')));
//session
app.use(session({
secret: 'randomstringhere',
resave: false,
saveUninitialized: false,
cookie: {
}
}));
app.get('/', (req, res) => {
if (req.session.login) {
res.redirect('/dashboard');
}
else {
res.sendFile(__dirname + '/views/login.html');
console.log("Someone has joined to the server.");
io.on('connection', (socket) => {
//login
socket.on('login', (login, password) => {
con.query('SELECT * FROM users WHERE login="'+login+'" AND password="'+md5(password)+'"', (error, results, fields) => {
if (error) console.log('Error');
if (results[0]) {
req.session.login = results[0].login;
console.log(req.session.login+": Succesfully logged.");
req.session.save();
socket.emit('logged', 'You will be logged, please wait!');//redirects to /dashboard
}
else {
socket.emit('cant login', 'Login or password incorrect!');
console.log("Incorrect login or password.");
}
});
});
});
}
});
app.get('/dashboard', (req, res) => {
if (req.session.login) {
res.sendFile(__dirname + '/views/index.html');
console.log(req.session.login + " has joined to the server.");
io.on('connection', (socket) => {
socket.on('message', (msg) => {
io.emit('message', req.session.login + ": " + msg);
console.log(req.session.login + ": " + msg);
});
//logout
socket.on('logout', () => {
socket.emit('logging out');
req.session.destroy();
});
});
}
else {
res.redirect('/');
}
});
var express = require('express')
var app = express()
var server = require('http').createServer(app)
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi')
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: true
})
nodeSSPIObj.authenticate(req, res, function(err){
res.finished || next()
})
})
app.use(function(req, res, next) {
id = req.connection.userSid
res.redirect('Full_Name.html')
res.send
})
// Start server
var port = process.env.PORT || 3000
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.get('env'))
})
I am new to node.js . I am trying to redirect to a page after successfully login . but facing error
localhost redirected you too many times.
and i dont know why but this javascript is not behaving same on firefox compared to other browsers .
I just want to redirect to Full_Name.html page after successfull login .
Yeap, you are using an express.js middleware without a route or any specific handling meaning that the redirect takes place across all the registered routes.
You may specify a redirect for a specific route as:
app.use('/redirect_me', function (req, res, next) {
// This middleware is triggered across all methods
// POST, GET, PUT etc;
res.redirect('Full_Name.html');
});
you have to redirect to a route not to a page:
app.use(function(req,res,next){
id = req.connection.userSid;
// do some check
res.redirect('/your-target-route');
next();
})
app.get('/your-target-route',function(req,res){
res.send('Full_Name.html');
});
Use this,
app.get('/Full_Name', function(req, res) {
res.sendFile(__dirname + "/public/Full_Name.html"); //path to ur file
});
res.redirect("/Full_Name"); //use wherever required
//You need to redirect the user to a webpage and not a file
I would use socket.io in my routes file.
I have found multiple methods but no one worked for me.
Now I'm trying this solution
var http = require("http");
var admin = require('firebase-admin');
var firebase = require("firebase");
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.app_port || 8080; // set our port
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(port);
var io = require("socket.io")(server);
var routerProj = require("./routes/routes")(io);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,*");
next();
});
var config = {
XXX
};
firebase.initializeApp(config);
var serviceAccount = require("./ServiceAcountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://datatable-18f93.firebaseio.com"
});
app.use("/v1", routerProj);
//Create HTTP server and listen on port 8000 for requests
// Print URL for accessing server
console.log("Server running at http://127.0.0.1:8080/");
io.sockets.on("connection", function (socket) {
console.log("a user is connected");
});
Routes.js
var express = require("express"); // call express
var router = express.Router(); // get an instance of the express Router
var admin = require("firebase-admin");
module.exports = function (io) {
/*router.use(function (req, res, next) {
// do logging
io.on('connection', function (socket) {
console.log('User has connected to Index');
});
});*/
router.use(function (req, res, next) {
io.on('save-message', function (socket) {
console.log('User has connected to Index');
});
});
router
.route("/")
.get(function (req, res, err) {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.once("value", function (snapshot) {
var list = [];
snapshot.forEach(function (elem) {
list.push(elem.val());
})
list = JSON.stringify(list);
//list = JSON.parse(list)
//console.log(JSON.stringify(list))
res.send(list);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
res.status(500).send(errorObject.code);
});
});
router
.route("/")
.post(function (req, res, err) {
console.log(req.body);
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("/");
// Attach an asynchronous callback to read the data at our posts reference
ref.push(
{
"text": req.body.text
}
);
});
return router
}
sockets are working in my server.js file , in console I get the message :"a user is connected" when I run my angular app.
But in my browser I run http://127.0.0.1:8080/v1in router.js console.log is not working, so sockets is not getting passed.
I have tried to emit an event :
ngOnInit() {
this.socket.emit('save-message', { room: "hello" });
}
In my router.js :
router.use(function (req, res, next) {
io.on('save-message', function (socket) {
console.log('User has connected to Index');
});
});
console.log don't print anything.
I'm trying to create a REST API using Node.js that would fetch the last N rows of a MongoDB collection. This is my current code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var mongodb = require("mongodb");
var MongoClient = require("mongodb").MongoClient;
var db;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/sample", function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
}).limit(10,function(e,d){});
});
app.use('/',router);
app.listen(3000);
console.log("Listening to PORT 3000");
This is successfully printing out all of the contents of the database on the server console (Whenever the client makes a get request). However, how do I give this JSON information to the client making the GET call instead in an efficient way (and one that supports the situation where the client can add a parameter N that would only fetch the last N rows of the database). I looked into Mongoose and that seemed pretty solid but in my case I already have a pre-existing database and collection so wasn't sure if that was the best route for this task.
If you need any more info or clarification, feel free to let me know! Thanks for reading!
Instead of res.end, you would use res.send and send the response back to the front end.
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
var response = {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.parse(doc)
}
res.send(response);
}
});
});
});
To get the last N records of a collection, you could use a combination of sort and limit. First, sort on a specific field such as date in ascending/descending order and then limit the results to whatever N is. Something like this:
db.collection.find({ query }).sort({ key: 1 }).limit(N)
UPDATE:
Based on our ongoing comment conversation, here is an example of how I have successfully sent data back to the client. This does not include the limit or anything fancy.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var db = require('./config/db');
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/', function(req, res) {
db.find({}, function(err, data) {
if (err) {
console.log(err);
return res.send(500, 'Something Went wrong with Retrieving data');
} else {
// console.log(data[0]);
res.json(data);
}
});
});
app.listen(port);
console.log('Server listening on port: ', port);
Ended up fixing my issue. Changed my get statement to this:
router.get("/", function(req, res, next) {
db.collection("samplecollection", function(err, collection){
collection.find({}).limit(10).toArray(function(err, data){
res.json(data);
})
});
});
This is my Express middleware stack:
var server = express()
.use(express.cookieParser())
.use(express.session({secret: 'Secret'}))
.use(express.bodyParser())
.use(function printSession(req, res, next) {
console.log(req.session.user);
next();
})
.use(express.static('./../'));
and here are two routes:
server.post('/setSession', function (req, res) {
req.session.user = 'admin';
}
server.post('/getSession', function (req, res) {
console.log(req.session.user);
}
Now the session management in the route handlers work find. I can set session.user and it will persist for the subsequent requests in the same session, as confirmed by getSession. However, the middleware function printSession always prints undefined.
How can I access the populated session object in the middleware?
This program works fine. Before I access /setSession, the middleware prints after session: undefined. Once I GET /setSession, it prints after session: admin. As long as the browser you are testing with (not curl) stores and sends the session cookies, this will work as expected.
var express = require('express');
var server = express();
server.use(express.cookieParser());
server.use(express.session({secret: 'SEKRET'}));
server.use(function (q,r,n) {console.log('after session:', q.session.user);n();});
server.get('/', function (q,r,n) {r.send("you got slashed");});
server.get('/setSession', function (req, res) {
console.log("logging admin in via /setSession");
req.session.user = 'admin';
res.send("admin logged in");
});
server.listen(3000);
There must be something wrong with your settings. The following example, that is very similar to your code but uses GET instead POST, works fine for me
app.configure(function(){
// ...
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(function(req, res, next) {
console.log(req.session.user + ' from middleware');
next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
and
app.get('/getSession', function(req, res) {
console.log(req.session.user);
res.send('awesome');
});
app.get('/setSession', function(req, res) {
req.session.user = 'admin';
res.send('done');
});
Now when you do the following everything works as expected
GET /getSession => undefined from middleware, undefined
GET /setSession => undefined from middleware
GET /getSession => admin from middleware, admin