socketstream tutorials/authentication can't use Everyauth with the chat demo - javascript

https://socketstream.github.io/socketstream/docs/#/tutorials/authentication
when i put the codes in this section to the demo project(real time chat), the chat function doesn't work. can any one help me with this?
here's my code:
// ===================== SEPARATOR ============
var ss = require('socketstream');
var redirect = require('connect-redirection');
var everyauth = require('everyauth');
var http = require('http');
var conf = require('./conf/conf');
var auth_twitter = conf.oauth.twitter;
// Define a single-page client called 'main'
ss.client.define('main', {
view: 'app.html',
css: ['../node_modules/normalize.css/normalize.css', 'app.css'],
code: ['../node_modules/es6-shim/es6-shim.js', 'libs/jquery.min.js', 'app'],
tmpl: 'chat'
});
ss.http.middleware.prepend(redirect());
// Serve this client on the root URL
ss.http.route('/', function(req, res){
// if(!req.session.userId){ return res.redirect('/login'); }
res.serveClient('main');
});
// Use server-side compiled Hogan (Mustache) templates. Others engines available
ss.client.templateEngine.use(require('ss-hogan'));
// Minimize and pack assets if you type: SS_ENV=production node app.js
if (ss.env === 'production') ss.client.packAssets();
everyauth.twitter
.consumerKey(auth_twitter.KEY)
.consumerSecret(auth_twitter.SEC)
.findOrCreateUser( function (session, accessToken, accessTokenSecret, twitterUserMetadata) {
var userName = twitterUserMetadata.screen_name;
console.log('Twitter Username is', userName);
session.userId = userName;
session.save();
return true;
})
.redirectPath('/');
var bodyParser = require('body-parser');
//ss.http.middleware.prepend(bodyParser.urlencoded());
//ss.http.middleware.append(everyauth.middleware());
var server = http.Server(ss.http.middleware);
server.listen(3000);
ss.start(server);

After reading some doc, i tried this and it worked:
replace the last three lines codes:
var server = http.Server(ss.http.middleware);
server.listen(3000);
ss.start(server);
with this:
ss.start();

Related

How to send data between Node js and javascript in an html file

I am using an eye tracker and I want to create a website that displays this data in real time. I have the eye tracker notifying a Node js server and it provides data really consistently but when I used socket.io to send the data over it was buffering really slowly. I want a way to receive this data in a script in my index.html from the Node js server in real time or as close as possible. Any suggestions?
I have found my solution in socket.io-streams. Here's what I did:
in the app.js:
var ss = require('socket.io-stream');
var Readable = require('stream').Readable;
const io = require('socket.io')(http);
io.of('/data').on('connection', socket => {
var eyeTracker = ...
var listener = {
...
onGazeData:function(gazeData){ //trigger for recieving a gaze location
var s = new Readable()
s._read = function() {};
var stream = ss.createStream();
toSend = gazeData.x + "," + gazeData.y
s.push(toSend);
s.pipe(stream);
ss(socket).emit('gaze',stream);
}
}
eyeTracker.setListener(listener);
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
}
and in the index.js (linked to index.html) I put:
var ss = require('socket.io-stream');
$(function(){
var socket = io.connect('http://localhost:3000/data'); //or where ever you are running
socket.on('connect', function() {
ss(socket).on('gaze', function(stream) {
stream.on('data', function(data) {
//do what you want with data
})
})
});
//other parts of script outside of socket
});
This solution was able to keep up with the data being streamed.

app.get('') is not working in node js with query parameters

Iam trying to provide a new route for my conversation application where it should accept the parameters passed along with the route should be accepted and can be used in client side.But I couldnt figure out why basic .get() is not working ,where Iam unable to render the html.
'use strict';
var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
var bodyParser = require('body-parser');
var app = express();
app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());
app.get('/:id',function(req,res){
var userid = req.params.id;
var pid = req.query.pid;
res.sendFile(__dirname,'/public/index.html');
});
module.exports = app;
On my localhost:3000 index file is getting loaded but for something like localhost:3000/3405?pid=CBM it is not loading.
Then I have a js file on client side which would require these two values id and pid.For now I just hardcoded.But how can I use these values to client side js file..Can someone help me how can I do this...
Thanks
Updated :Adding my client side js file
var Api = (function() {
var messageEndpoint = '/api/message';
var emp = {
"pid": "CBM",
"id": "3405",};
return {
sendRequest: sendRequest,
modifytext: function(intent, text) {
if (intent == "Hello") {
console.log(text, "Inside intent");
for (var key in emp) {
var tempKey = '{{' + key + '}}';
var tempValue = emp[key];
text = replace(text, tempKey, tempValue);
console.log("came back");
}
}
return text;
console.log(text,"Final text");
}
};
function replace(text, originalString, replaceText) {
console.log("Reached replace functions", text, originalString, replaceText);
if (replaceText)
text = text.replace(originalString, replaceText);
else
text = text.replace(originalString, "");
return text
}
}());
This is incorrect:
res.sendFile(__dirname,'/public/index.html');
It should be this:
res.sendFile(__dirname + '/public/index.html');
Or (a bit more robust):
const path = require('path');
...
res.sendFile(path.join(__dirname, 'public/index.html'));
As a side note: apparently, if you pass a directory name to res.sendFile(), it will send back a 404 response. Not sure that the rationale behind that is.

Pass a parameter to another JavaScript and run the script

Send a parameter(URL) from another script through recursion to this script.
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var murl = 'mongodb://localhost:27017/getData';
url = '';
app.get('/getData', function(req, res){
firstCall(req,res)
//console.log("cookie",req.cookies);
})
var firstCall = function(req, res, data){
console.log("URL: ", url);
res.send('Check your console!');
}
app.listen('3000')
console.log('Magic happens on port 3000');
module.exports = function(app) {
app.get('/getData', function() {});
};
I want this code to act as backbone or logic board. And some other file should be able to trigger this logic board file by adding the URL to this file.
Like we pass parameters to function to call. How do I do it here.

combining functionality of two Node servers with different initial set up

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?
You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

Creating a javascript object and binding this

I'm trying to build my first node app. My app.js file is shown below. I want to access this from aother module by doing 'app = require('app')'. I then want to access app.app, app.dbConn and app.models
The problem is that when I require this module, app.models is not present on the resulting object.
var express = require('express');
var path = require('path');
var orm = require('orm');
var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');
module.exports = new function(){
this.app = express();
// middlewares must be added in order - start with the basics
environment(this.app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }
// add models to the request early in the middleware chain
this.dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
this.models = db.init(this.dbConn);
this.app.use(function(req,res,next){
req.models = this.models;
next();
});
passport = auth.init(this.models);
authRouter = auth.router(passport)
this.app.use('/users', authRouter);
this.app.use(mainRouter);
}
}.bind(this));
this.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
}
The only way to implement what I wanted was with a function that takes a callback, in the end I rewrote my code thus:
var express = require('express');
var path = require('path');
var orm = require('orm');
var settings = require('./config/settings');
var mainRouter = require('./config/routes');
var environment = require('./config/environment');
var db = require('./config/db');
var auth = require('./modules/auth');
var app;
module.exports = function(cb){
app = express();
// middlewares must be added in order - start with the basics
environment(app);
if (process.env.TESTING) { dbSettings = settings.dbTesting; }
else { dbSettings = settings.db; }
// add models to the request early in the middleware chain
dbConn = orm.connect(dbSettings, function(err){
if (err) return console.error('DB Connection error: ' + err);
else{
models = db.init(dbConn);
app.use(function(req,res,next){
req.models = models;
next();
});
passport = auth.init(this.models);
authRouter = auth.router(passport)
app.use('/users', authRouter);
app.use(mainRouter);
cb({
dbConn: dbConn,
app: app,
models: models
});
}
});
}
if (!process.env.TESTING) {
module.exports(function(server){
server.app.listen(settings.port);
console.log('Server started... listening on port ' + settings.port)
});
}
app.models is defined only once database connection is completed: you cannot use it right away after requiring the module. You should provide an entry point that accepts a function to call once the connection is ready and call this function inside the orm.connect callback.
Even the "server started" message is a bit misleading as it's shown before the server can actually do anything because the function passed to orm.connect has not been called yet.
app.models is never defined so it is never available.
Instead, try
app.set('models', db.init(this.dbConn);

Categories

Resources