While in / view, I get documents from mongodb and create a list item for each document that only shows the date and the first few words. I want to be able to click on each list item to go to a new page, /view, to see the rest of that particular document.
To do this, I believe I need to pass item between / and /view, then access the properties of item there. How do I do this with the pagelist function (or without it)?
index.js:
var express = require('express');
var exphbs = require('express-handlebars');
var bodyParser = require('body-parser');
var app = express();
var hbs = exphbs.create({
helpers: {
message: function() {return 'Welcome!';},
doc: function() {return "Something went wrong.";}
}
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var util=require('util');
const url = 'mongodb://localhost:27017/users';
const dbName = 'users';
var db;
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
db.collection("reviewYelp2", { }, function(err, coll) {
if (err != null) {
console.log(err)
db.createCollection("reviewYelp2", function(err, result) {
assert.equal(null, err);
});
}
db.ensureIndex("reviewYelp2", { document: "text"}, function(err, indexname) {
assert.equal(null, err);
});
});
});
app.get("/", function(req, res) {
res.render('search');
});
app.get("/view", function(req, res) {
// NEED TO BE ABLE TO ACCESS CLICKED ITEM HERE
res.render('viewItem', {
// Change to access item.text when I have access to item
helpers: {
doc: function() {return "Viewing doc...";}
}
});
});
app.post("/", function(req, res) {
db.collection('reviewYelp2').find({
text: new RegExp(req.body.query)
}).sort({date: 1}).toArray(function(err, items) {
res.render('search', {
helpers: {
message: function() {return pagelist(items);}
}
});
})
});
function pagelist(items) {
result = "<ul>";
items.forEach(function(item) {
// Grab only first 10 words of text
textSlice = item.text.split(" ");
textSlice = textSlice.slice(0, 5);
text = textSlice.join(" ");
str = "<li class="+item._id+"><a href='/view'>" + item.date + " " + text + "...</a></li>";
result = result + str;
});
result = result + "</ul>";
return result;
}
app.listen(3000, function() {
console.log("App listening on localhost:3000");
});
search.handlebars:
<!DOCTYPE html>
<html>
<body>
<form method="post">
<input type="text" size="80" name="query" />
<input type="submit" value="Search" class="submitButton" />
{{{ message }}}
</form>
</body>
</html>
viewItem.handlebars:
<!DOCTYPE html>
<html>
<body>
<button onclick="window.history.back()">Go back to list</button>
{{{ doc }}}
</body>
</html>
This is problematic because http is fundamentally stateless — that is each request to the server is it's own thing. You can come up with schemes involving cookies or local storage, but I think a simpler approach is both better and more common.
A simpler idea is to have a route that takes some sort of id parameter:
app.get("/view_detail/:itemID", function(req, res) {
var item = req.params.itemID
// lookup detail about item based on itemID
res.render('viewItem', {
// send data
});
});
Now on index you can have a list of links that look like :
/view/878743 (or whatever scheme you have for db keys)
/view/36764e
Related
I am newbie to NodeJs..
I have a home page with select option to select the testcase..
1. DB value from Node js to populate the select option
2. Need to select the value in the dropdown list
3. Need to run the query and populate the query results on table on the same page..
\views\index.ejs
Name
Login
<section class="home">
<h1>Table</h1>
<ol class="list-group">
<% for(var i=0; i<listVals.length; i++) {%>
<li class="list-group-item">
<span>Case: </span><%= listVals[i].Case_Id %>
<span>Run: </span><%= listVals[i].Run_Id %>
<span>Status: </span><%= listVals[i].Status %>
<span>NoofAttempts: </span><%= listVals[i].Attempts %>
</li>
<% } %>
</ol>
</section>
appnew.js
var express = require('express');
var app = express();
var ejs = require('ejs');
var bodyParser = require("body-parser");
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(express.static("public"));
var sql = require("mssql");
// config for your database
var config = {
user: 'sa',
password: 'password',
server: 'MAA-LTC821Z33\\SQLEXPRESS',
database: 'master',
"options": {
"encrypt": true,
"enableArithAbort": true
}
};
app.get('/', function (req, res) {
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select Distinct(Case_Id) from TestRail', function (err, recordset) {
if (err) console.log(err)
console.log(recordset)
var runId = "R12345";
res.render("index", { run: runId, dropdownVals: recordset.recordset });
});
});
});
app.get("/", (req, res) => {
res.render("index");
});
app.post("/login", (req, res) => {
const { nameof} = req.body;
console.log(nameof)
/* if (nameof === "C6706") {
res.render("success", {
username: nameof,
});
} else {
res.render("failure");
}*/
req.query("select * from TestRail where Case_Id='nameof'", function (err, recordset) {
if (err) console.log(err)
res.send(recordset);
})
});
app.listen(3000, () => {
console.log("server started on port 3000");
});
I am able to get the passed value on submit.. but after submitting i need to render the sql query results..
when I run that listVals is not defined.
Thanks
First off, in your node portion, it looks like you are using
app.get('/', function (req, res) {
two times for the same route..
Second, what error are you getting?
In general, the process you have for passing the query to ejs should work ( minus the other endpoint.) then in ejs you just access that passed variable like
<%for ( in in listVals){%>
<options value="<%-listVals[i].value%>">text</options>
<%}%>
This is my first web dev project. I am basically trying to make a simple website to sell light sabers. The goal is to be able to create an account, login, add, edit and delete light sabers. Be able to add them to cart and checkout. I am using node.js, express, and mongoDB in visual studio code. I am also learning github throughout the process. As of now I have the layout of the website mostly set up. Am able to create accounts and login. I am currently stuck on creating items(light sabers) and saving them in the mongoDB database. Specifically my http methods in the routes/items files are not working, they were working previously in the app.js file but I decided to move everything for organizational purposes. Again, this is my first time working with any of this tech and this project is a work in progress, any input is appreciated. Thanks.
Here is my code: There is a lot of code not being used and its kind of a mess. I know..
app.js file:
const express = require("express");
const session = require("express-session");
var mongoose = require("mongoose");
var passport = require("passport");
var bodyParser = require('body-parser');
var localStrategy = require('passport-local');
var passportLocalMongoose = require("passport-local-mongoose");
var router = express.Router();
const app = express();
const indexRouter = require('./routes/index')
const itemsRouter = require('./routes/items')
//npm install ejs body-parser mongoose passport passport
var uri = "mongodb://username:password#cluster0-shard-00-00-
hnxfk.mongodb.net:27017,cluster0-shard-00-01-
hnxfk.mongodb.net:27017,cluster0-shard-00-02-
hnxfk.mongodb.net:27017/test?
ssl=true&replicaSet=Cluster0-shard-
0&authSource=admin&retryWrites=true&w=majority";
var localHost = "mongodb://localhost:27017/Project2SamJoshEricRoy"
mongoose.connect(uri,{useNewUrlParser: true, useUnifiedTopology:
true });
var User = require('./models/user');
var Item = require('./models/item');
// var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(require('express-session')({
secret: "application secret shhhh",
resave: false,
saveUninitialized: false
}));
passport.use(new localStrategy(User.authenticate()))
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter)
app.use('/items', itemsRouter)
//create account
app.get("/createAccount",(req,res)=> {
res.render("createAccount");
});
app.get('/createAccount', function(req,res) {
res.render('createAccount');
});
app.post("/createAccount",(req,res)=> {
req.body.username;
req.body.password;
User.register(new
User({username:req.body.username}),req.body.password,
(err,user) =>{
if(err) {
console.log(err);
return res.render("createAccount");
}
passport.authenticate("local")(req,res,() => {
res.redirect('/login');
console.log(req.body.username
+ " " + req.body.password);
console.log(user);
});
});
});
//login
app.get("/login",(req,res) => {
res.render("login")
User.find(function(err,users) {
if(err) {
console.log(err);
}
// console.log(users);
})
});
app.post('/login',passport.authenticate("local",{
successRedirect: "/lightsabers",
failureRedirect: "/login"
}),(req,res)=> {
});
function isLoggedIn(req,res,next) {
console.log("CALL")
if(req.isAuthenticated()) {
console.log("logged in ");
return next();
}
res.redirect("/login");
console.log("error logging in");
}
//logout
app.get("/logout",(req,res)=> {
req.logout();
res.redirect('/');
});
//lightsabers
//app.get("/lightsabers",isLoggedIn,(req,res)=> {
//res.render("lightsabers",{user: req.user});
//console.log(req.user);
//});
//shopping cart
app.get("/cart",(req,res)=> {
res.render("cart");
});
app.get('/createLightsaber',(req,res)=> {
res.render("newItem",{user:req.User});
console.log("user is with us");
console.log(req.user)
});
app.get('/updateItem',(req,res)=> {
res.render("updateLightsaber");
});
app.get('/deleteLightsaber',(req,res)=> {
res.render("updateLightsaber");
});
/routes/index.js file:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.render('index')
})
module.exports = router
routes/items.js
const express = require('express')
const router = express.Router()
const Item = require('../models/item')
//display page
router.get("/",(req,res)=> {
res.render("newItem");
});
// all items route
router.get('/', async (req, res) =>{
try{
const items = await Item.find({})
res.render('items/newItem', {item: new Item() })
} catch {
res.redirect('/')
}
})
//new item route (display form)
router.get('/newItem', (req, res) => {
res.render('items/newItem', {item: new Item() })
})
// create new item route (actual creation)
router.post('/newItem', async (req,res) => {
const item = new Item({
color:req.body.color,
price:req.body.price,
link:req.body.link
})
try{
const newItem = await item.save()
res.redirect('lightsabers')
} catch {
res.render('items/newItem', {
item: item,
errorMessage:'Error creating item'
})
}
})
/update item
app.get("/updateItem",(req,res)=> {
res.render("updateItem");
});
module.exports = router
newItem.ejs
<!DOCTYPE html>
<html>
<head>
<title> </title>
<link rel="stylesheet" href="/css/styles.css"/>
</head>
<body>
<h1> Adding New Item </h1>
<form action="/items" method="POST">
<h2>
Color: <input type="text" name="color"><br>
Price: <input type="text" name="price"><br>
Image Link:<input type="text" name="link"><br>
<br><br>
<button id="addItem">Add Item</button>
<%= typeof(message) != "undefined"?message:"" %>
</h2>
</form>
<form action="/lightsabers">
<h2><button> Back </button></h2>
</form>
<script type="text/javascript" src="../public/app.js">
</script>
</body>
</html>
If you wish to see any other parts of the code let me know. I may be forgetting something important.
I am having an issue with trying to save data parsed from the browser to my mongodb database it would be great if someone could explain to me why I am getting the error I am and how to fix it, thanks.
App.js:
var print = require('./print');
var port = 1338;
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:1337/testdb';
MongoClient.connect(url, function(err, db) {
var collection = db.collection('users');
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
}
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
var collection = db.collection('users');
var name = app.post('/post', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
var name = req.body.name
var user1 = { "username": name };
collection.insert(user1, function(err, result) {
if (err) {
console.log(err);
} else {
console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
}
})
});
app.listen(port, function() {
print(`listening on ${port}`);
})
db.close();
})
Post.ejs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="http://127.0.0.1:1338/post" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
Error:
{ MongoError: server instance pool was destroyed
at Function.MongoError.create (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\error.js:29:11)
at basicWriteValidations (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:446:51)
at Server.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb-core\lib\topologies\server.js:532:16)
at Server.insert (C:\Users\Programming\Documents\Web_Repo\\node_modules\mongodb\lib\server.js:383:17)
at executeCommands (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:455:23)
at OrderedBulkOperation.execute (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\bulk\ordered.js:508:10)
at bulkWrite (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:652:8)
at Collection.insertMany (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:522:44)
at Collection.insert (C:\Users\Programming\Documents\Web_Repo\node_modules\mongodb\lib\collection.js:824:15)
at C:\Users\Programming\Documents\Web_Repo\app.js:36:18
name: 'MongoError',
message: 'server instance pool was destroyed' }
Looks like Mukesh already told you the solution but like he mentioned your code structure can be improved.
So here's how I would do it,
Config file ~config.js
module.exports = {
localUrl: 'mongodb://localhost/testDb',
port: 1338
};
main file
var print = require('./print');
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var config = require('./config.js');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render("post");
print("All is in order");
})
app.listen(config.port, function() {
print(`listening on ${config.port}`);
})
MongoClient.connect(config.localUrl, function(err, db) {
if(err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collection = db.collection('users');
app.post('/post', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
collection.insert({
username : req.body.name
}, function(err, result) {
if (err) {
console.log(err);
db.close();
return;
}
db.close();
})
});
})
My project goal is to make a checklist-like web app where the user can see what's in the database and also update what's inside it.
Database is simple. Just listing favorite things. Eg {"favorite":"Pie"},{"favorite":"Kitty"}
So far I've figured out how to connect to the database(MongoHQ) and show a single element of data. I've been trying for hours but I'm stumped on:
Getting the html file to write whatever data is in the database.
Writing the Post form to write to the database.
Please share some insights!
Here's my code.
.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<h1>Notepad</h1>
<p>Favorite things: {{favorite}}</p>
<!-- {% for favorite in doc %} <-this doesn't work!
<p>Favorite things: {{favorite}}</p>
{% endfor %}
-->
</div>
</body>
</html>
web.js
var express = require('express');
var path = require('path');
var fs = require('fs');
var http = require('http');
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var Server = require('mongodb').Server;
var mongoUri = "mongodb://id:pass#ds------.mongolab.com:-----/heroku_app------";
var cons = require('consolidate');
var app = express(express.logger());
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.set('port', process.env.Port || 8080);
app.use(express.bodyParser());
var mydatabase = null;
var myCollection = null;
MongoClient.connect(mongoUri, function(err, db){
if(!err){
console.log("We are connected to mongo_lab!");
}
mydatabase = db;
mydatabase.createCollection('test2', function(err, collection){});
myCollection = mydatabase.collection('favorites');
//myCollection.insert({'favorite':'Blueberries'}, {w:1}, function(err, result){});
});
var mongoclient_server = new MongoClient(new Server('localhost', 27017));
function errorHandler(err, req, res, next){
console.error(err.message);
console.error(err.stack);
res.status(500);
res.send("Fix the dam Error!");
}
app.use(errorHandler);
app.get('/notepad', function(req, res, next){
MongoClient.connect(mongoUri, function(err, db){
mydatabase.collection("favorites").find().toArray(function(err, doc){
if(err) throw err;
console.log(doc);
res.render('notepad', doc[0]);
});
});
});
var htmlfile = "index.html";
app.get('/', function(request, response) {
var html = fs.readFileSync(htmlfile).toString();
response.send(html);
});
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log("Listening on " + port);
});
//mongoclient_server.open(function(err, mongoclient_server){ <--if I use this, heroku crashes
// if(err) throw err;
// app.listen(port);
//});
You're passing data from doc[0] as locals to your notepad view, so basically notepad locals will be what is in doc[0].
In your call to res.render(), you should specify that your documents reside in the doc local, like this:
res.render('notepad', {
doc: doc
});
This way your {% for ... %} will work.
Docs for res.render
After struggling a lot with session.socket.io module, I decided to do my socket-session linking by setting authorization for my socket.io. Here is my server:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var io = require('socket.io');
var redis = require('redis');
var crypto = require('crypto');
var redisClient = redis.createClient();
var app = express();
// Session Tracking
var cookieParser = express.cookieParser('secret');
var RadisStore = require('connect-redis')(express);
var sessionStore = new RadisStore({
host: '127.0.0.1',
port: 6379,
db: 10,
client:redisClient
});
// Redis Client Used to store user Information
var redisUsersClient = redis.createClient();
const userDB = require('redis-user')(redisUsersClient);
var PORT = process.env.PORT || 3000,
HOST = process.env.HOST || 'localhost';
// We define the key of the cookie containing the Express SID
var EXPRESS_SID_KEY = 'express.sid';
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
app.use(express.methodOverride());
app.use(cookieParser);
app.use(express.session({ store: sessionStore,
secret: 'SEKR37',
cookie: { httpOnly: true},
key: EXPRESS_SID_KEY
}));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function(req, res){
if(!req.session.user)
res.redirect('/login')
else {
res.sendfile('chat.html')
}
});
app.get('/login', function(req, res){
res.render('login');
});
app.get('/register', function(req, res){
res.render('register');
});
app.get('/logout', function(req, res){
//console.log(req.session);
sessionStore.destroy(function(err){
console.log("there was an error: "+err);
});
req.session.destroy();
res.redirect('/login');
// redisUsersClient.hdel('users', req.session.user, function(err, reply){
// if(reply==1) {
//
// res.redirect('/login');
// }
// else
// res.send("you do not exist");
// });
});
app.post('/login',function(req, res){
var password = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.password).digest('utf8');
var username = req.body.username+"#mychat.com";
//console.log(req.session);
userDB.validateUser(username, password, function(result){
if(result)
{
req.session.user = username;
req.session.status = 1;
req.session.isLogged = true;
req.session.save();
res.redirect('/');
}
else
{
res.send("Wrong Credential. Please <a href='/login'>Try Again</a>");
}
});
});
app.post('/register',function(req, res){
var username = req.body.username + "#mychat.com";
var password = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.password).digest('utf8');
var verify = require('crypto').createHash('sha1WithRSAEncryption').update(req.body.verify).digest('utf8');
if(password==verify)
{
userDB.createUser(username, password, function(result) {
if (result) {
redisUsersClient.hset('users', username, password);
res.redirect('/');
} else {
res.send("could not create user, Something very unexpected happened");
}
});
}
else
{
res.send("Passwords do not match. please <a href='/register'>try again</a> " );
}
});
server = http.createServer(app);
io = io.listen(server);
/****
Maybe I have to set store for io?
****/
//io.set('store', sessionStore);
io.set('authorization', function (data, accept) {
if(!data.headers.cookie) {
return accept('No cookie transmitted.', false);
}
console.log(sessionStore);
cookieParser(data, {}, function(parseErr) {
if(parseErr) { return accept('Error parsing cookies.', false); }
var sidCookie = (data.secureCookies && data.secureCookies[EXPRESS_SID_KEY]) ||
(data.signedCookies && data.signedCookies[EXPRESS_SID_KEY]) ||
(data.cookies && data.cookies[EXPRESS_SID_KEY]);
console.log(sidCookie);
// Then we just need to load the session from the Express Session Store
sessionStore.load(sidCookie, function(err, session) {
// And last, we check if the used has a valid session and if he is logged in
console.log(session);
if (err || !session) {
accept('Error', false);
}
else {
// If you want, you can attach the session to the handshake data, so you can use it again later
data.session = session;
//console.log('success');
accept(null, true);
}
});
});
});
io.on('connection', function (socket) {
socket.on('add-user',function(data){
console.log(data.username);
clients.username = data.username;
//console.log(clients);
socket.broadcast.emit('entrance', data.username + ' has connected');
io.sockets.emit('add-user',{clients:clients});
});
socket.on('disconnect', function(){
delete clients[session.user];
io.sockets.emit('add-user',{clients:clients})
});
});
server.listen(PORT, HOST, null, function() {
console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});
And here is my client:
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- <script type='text/javascripts', src='/javascripts/client.js'></script> -->
<link rel='stylesheet', href='/stylesheets/style.css'>
<script>
jQuery(document).ready(function () {
var log_chat_message = function (message, type, divId) {
var li = jQuery('<li />').text(message);
if (type === 'system') {
li.css({'font-weight': 'bold','color': '#F00','cursor':'pointer'});
} else if (type === 'leave' || type === 'error') {
li.css({'font-weight': 'bold', 'color': '#F00'});
}
jQuery('#'+divId).append(li);
};
// connect to the socket server
var socket = io.connect();
socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
socket.on('welcome',function(data){
alert("yooooo");
var username = data.username.substr(0,data.username.indexOf('#'));
var message = "Welcome " + username ;
log_chat_message(message, 'system','messages');
socket.emit('add-user',{username: username});
});
socket.on('entrance', function(data){
//var message = data.username.substr(0,data.username.indexOf('#')) + " joined the chat";
log_chat_message(data, 'system','messages');
});
socket.on('add-user', function(data){
jQuery.each(data, function(key, value){
console.log(value.username);
log_chat_message(value.username, 'system','users-list');
})
});
jQuery('#message_input').keypress(function (event) {
if (event.which == 13) {
socket.emit('chat', {message: jQuery('#message_input').val()});
jQuery('#message_input').val('');
}
});
jQuery('#users-list li').on('click','li',function(){
alert('hi');
});
jQuery('#users-list li').click(function () {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
jQuery('#user').val('');
socket.emit('request', {username: jQuery('#user').val()});
});
});
</script>
<style type = 'text/stylesheet'>
#users-list li {
cursor:pointer;
}
</style>
</head>
<body>
<a href='/logout'>Log Out</a>
<div id="wrapper" style="width:80%;margin:0 auto;">
<!-- <input type="text" name="user" id="user"/>
<button id="submit" value="submit">Submit</button> -->
<div id='mainContaner' style="width:600px;height:400px;margin:0 auto;">
<div id="online-users" style="width:150px;float:left;height:400px;padding:20px;border:1px black solid;">
<ul id="users-list" style="list-style:none"></ul>
</div>
<div id= "container" style="width:350px;float:left;height:400px;padding:20px;overflow-y:scroll;border:1px black solid;">
<ul id='messages' style="list-style:none"></ul>
</div>
<input type="text" name="message_input" id='message_input' style="width:390px;height:30px;margin-left:193px;margin-top:5px;"/>
</div>
</div>
</body>
However, I get a handshake error. I am aware that I cannot get my session by loading my session store and that is why the error happens.
Please Advise
You should replace this line
sessionStore.load(sidCookie, function(err, session) {})
with this line
sessionStore.get(sidCookie, function(err, session) {})
This because there's no method load in connect-redis. Only get method
Also when you access your session in socket you can use socket.handshake.session.user