Nodejs:Unable to Pass variable from app.js to Index.html - node.js

I am struggling from two days to do this operation but failure.In App.js i have tried:-
var express = require('express'),
app = express(),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/data'));
app.get('./index',
function (req, res) {
res.render('index', {});
getUserInfo(req) //get your information to use it.
.then(function (userinfo) { //return your promise
res.json({ "name": userinfo.Name});
//you can declare/return more vars in this res.json.
//res.cookie('name', name); //https trouble
})
.error(function (e) {console.log("Error handler " + e)})
.catch(function (e) {console.log("Catch handler " + e)});
res.send('Hello World');
});
app.listen(8080);
My index.html code goes here
$.ajax({
url: '/index',
headers: {
Authorization: 'Bearer ' + idToken
},
processData: false,
}).done(function (data) {
localStorage.setItem('name', data.name);
//or whatever you want done.
}).fail(function (jqXHR, textStatus) {
var msg = 'Unable to fetch protected resource';
msg += '<br>' + jqXHR.status + ' ' + jqXHR.responseText;
if (jqXHR.status === 401) {
msg += '<br>Your token may be expired'
}
displayError(msg);
})
But unfortunately i get this error when i open index from local server:8080 :-
Cannot GET /

Try changing app.get('./index') to app.get('/index')

Related

How to show ldapatuh node jpegPhoto?

I use ldapauth-fork in node.js to take a user information in ldap but when I try to take a user.jpegPhoto why can't it show this image?
I've tried this:
const jpeg = Buffer.from(user.jpegPhoto, 'binary')
fs.writeFileSync("foto.jpeg", jpeg);
And this:
var img64 = Buffer.from(user.jpegPhoto).toString('base64');
var foto = "<div><img src='data:image/jpeg;base64,"+img64+"'/></div>"
fs.appendFile('index.html', foto, function (err) {
if (err) throw err;
console.log('Saved!');
});
This is all node.js code:
var basicAuth = require('basic-auth');
var LdapAuth = require('ldapauth-fork');
var http = require('http');
var fs = require('fs');
var qs = require('querystring');
var username = "MOCKUSERNAME";
var password = "MOCKPASSWORD";
server = http.createServer( function(req, res) {
if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function (data) {
body += data;
//console.log(body);
});
req.on('end', function () {
var data = qs.parse(body);
var userDecode = Buffer.from(data.username, 'base64').toString('ascii');
var passDecode = Buffer.from(data.password, 'base64').toString('ascii');
res.setHeader('Access-Control-Allow-Origin', '*');
res.writeHead(200, {'Content-Type':'image/jpeg'});
if (data.username && data.password) {
var options = {
url: 'XXXXXX',
bindDN: 'XXXXX',
bindCredentials: 'XXXXX',
searchBase: 'XXXXX',
includeRaw: true,
searchFilter: '(aoldapkey=*' + userDecode + ')'
// reconnect: true
}
var ldap = new LdapAuth(options);
ldap.authenticate(userDecode, passDecode, function(err, user) {
if (err) {
console.log("login Error: " + err);
res.write(JSON.stringify({ success : false, message : 'Authentication failed', serverError: err }));
res.end('');
} else if(!user.uid) {
console.log("user not found Error: " + err);
res.write(JSON.stringify({ success : false, message :
'Authentication failed, user not found', serverError: err }));
res.end();
} else if(user.uid) {
console.log("success : user "+ user.uid +" found ");
var userJsonObject = {
success : true,
user: {
uid : user.uid,
cn: user.cn,
givenName: user.givenName,
sn: user.sn,
title: user.title,
mobile: user.mobile,
mail: user.mail,
aoJobPosition: user.aoJobPosition,
jpegPhoto: user.jpegPhoto
}
}
//------------------------------dont see the image in index.html
/*var img64 = Buffer.from(user.jpegPhoto).toString('base64');
var foto = "<div><img src='data:image/jpeg;base64,"+img64+"'/>
</div>"
fs.appendFile('index.html', foto, function (err) {
if (err) throw err;
console.log('Saved!');
});*/
//--------------------------------
res.write(JSON.stringify(userJsonObject);
res.end();
}
});
} else {
res.write(JSON.stringify({ success : false, message : 'You must
specify a valid username and password'}));
res.end();
}
});
}
else {
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
}
});
server.on('error', function(err) {
console.log("Caught server error: ");
console.log(err.stack);
});
port = 3000;
host = '127.0.0.1';
server.listen(port, host);
console.log('Listening at http://' + host + ':' + port);
This is all node.js code I use ldapauth-fork in node.js to take a user information in ldap but when i try to take a user.jpegPhoto y canĀ“t show this image.
This is index.html :
<div><img src='data:imag/*;base64, 77x73..........3vv70='/></div>
index.html

How to get the responses from websocket server to client(socket.io) using nodejs

I included the socket.io.js in client and also included the custom created socket.js for getting the responses from websocket server to client,when i loading this page in browser automatically stopped the websocket server and in browser console tells WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket&sid=2p1ZYDAflHMHiL70AAAA' failed: Connection closed before receiving a handshake response
user defined socket.js code is given below
var socket = io();
var actionItems = []
var beginTakingAction = false
var strOut;
socket.on('transcript', function(x) {
var div = $('div.transcription')
div.html(x);
console.log("transcript " + x);
if (!scrolling) {
div.scrollTop(div[0].scrollHeight);
}
})
socket.on('action', function(x) {
console.log('sending action',x);
actionItems.push(x)
$('div.action').html(actionItems[actionItems.length-1]);
})
socket.on('sentiment', function(x) {
sentimentChart.update(x)
})
socket.on('nlp', function(x) {
wordLengthDistChart.update(x.wordLenghDist);
posTagDistChart.update(x.posTagDist);
})
socket.on('keywords', function(x) {
keywordChart.update(x)
})
socket.on('status', function(status) {
$('div.status').html("status: " + status);
if (status == "connected") {
sentimentChart.reset()
keywordChart.reset()
wordLengthDistChart.reset()
posTagDistChart.reset()
$('div.transcription').html('');
}
})
please give any suggesstions??
my server code is given below
require('dotenv').config()
var WebSocketServer = require('websocket').server;
var http = require('http');
var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();
const fs = require('fs');
const winston = require('winston')
winston.level = process.env.LOG_LEVEL || 'info'
var AsrClient = require('./lib/asrClient')
var asrActive = false
var myAsrClient;
var engineStartedMs;
var connections = []
//Create a server
var server = http.createServer(function(req, res) {
handleRequest(req,res);
});
// Loading socket.io
var io = require('socket.io').listen(server);
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
winston.log('info','A client is connected!');
});
var wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true,
binaryType: 'arraybuffer'
});
//Lets use our dispatcher
function handleRequest(request, response){
try {
//log the request on console
winston.log('info', 'handleRequest',request.url);
//Dispatch
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
dispatcher.setStatic('/public');
dispatcher.setStaticDirname('public');
dispatcher.onGet("/", function(req, res) {
winston.log('info', 'loading index');
winston.log('info', 'port', process.env.PORT)
fs.readFile('./public/index.html', 'utf-8', function(error, content) {
winston.log('debug', 'loading Index');
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Serve the ncco
dispatcher.onGet("/ncco", function(req, res) {
fs.readFile('./ncco.json', function(error, data) {
winston.log('debug', 'loading ncco');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(data, 'utf-8');
});
});
dispatcher.onPost("/terminate", function(req, res) {
winston.log('info', 'terminate called');
wsServer.closeAllConnections();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end();
});
wsServer.on('connect', function(connection) {
connections.push(connection);
winston.log('info', (new Date()) + ' Connection accepted' + ' - Protocol Version ' + connection.webSocketVersion);
connection.on('message', function(message) {
if (message.type === 'utf8') {
try {
var json = JSON.parse(message.utf8Data);
winston.log('info', "json", json['app']);
if (json['app'] == "audiosocket") {
VBConnect();
winston.log('info', 'connecting to VB');
}
} catch (e) {
winston.log('error', 'message error catch', e)
}
winston.log('info', "utf ",message.utf8Data);
}
else if (message.type === 'binary') {
// Reflect the message back
// connection.sendBytes(message.binaryData);
if (myAsrClient != null && asrActive) {
winston.log('debug', "sendingDate ",message.binaryData);
myAsrClient.sendData(message.binaryData)
}
}
});
connection.on('close', function(reasonCode, description) {
winston.log('info', (new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
wsServer.closeAllConnections();
});
});
wsServer.on('close', function(connection) {
winston.log('info', 'socket closed');
if (asrActive) {
io.sockets.emit('status', "disconnected");
winston.log('info', 'trying to close ASR client');
myAsrClient.close();
myAsrClient = null;
asrActive = false;
}
else {
winston.log('info', 'asr not active, cant close');
}
})
wsServer.on('error', function(error) {
winston.log('error', 'Websocket error', error);
})
var port = process.env.PORT || 8000
server.listen(port, function(){
winston.log('info', "Server listening on :%s", port);
});

http.get didn't get anything in nodejs

There's the code in my project which try to get an access token from wechat.
router.get('/', function(req, res, next) {
var params = new URLSearchParams({
grant_type: config.grantType,
appid: config.appID,
secret: config.appSecret
});
const url = config.wechat + '?' + params.toString();
http.get(url, (res) => {
console.log("haha");
console.log(res);
var rawData = '';
if (res.statusCode != 200) {
res.resume();
console.error('statusCode:' + res.statusCode);
return;
}
res.on('data', function (chunk) {
rawData += chunk; //buffer data if has
console.log(rawData);
});
res.on('end', function() {
try {
console.log("haha");
const accessTokenData = JSON.parse(rawData);
console.log("access: " + accessTokenData);
var newToken = new AccessToken({
token: accessTokenData["access_token"],
record_time: Date.now(),
expires: accessTokenData["expires_in"]
});
newToken.save(function(err) {
console.log("save error: " + err);
});
} catch (e) {
console.error('parse error: ' + e);
}
});
}).on('error', function(e) {
console.error("get access token failed: " + e);
});
console.log("sadfdas");
});
what I want to do is getting access token from the api and store it into mongodb using mongoose. when I start node service on my local vagrant machine and access the route, there is nothing printed on the terminal and new record inserted into mongodb. So I don't know where's the problem, I'm sure that the url is right, which I have tested with postman. Please help me find the problem. Any help will be appreciated.

Blocking requests coming from host A to host B nodejs

My nodejs httpserver (i'm not using express) is hosted in HOST A, domain: www.host-a.com and does this:
dispatcher.addListener("post", "/admin/insert_data", function(req, res) {
var body='';
req.on('data', function(chunk) {
body += chunk.toString();
});
req.on('end', function() {
var parsedbody = require('querystring').parse(body);
MongoClient.connect('mongodb://localhost:27017/database1', function(err, db) {
if (err) {
res.writeHead(500) ;
return res.end('Database offline') ;
}
console.log("Connected correctly to server");
var col = db.collection('mycollection');
col.insert(parsedbody, function() {
db.close();
var json = JSON.stringify({status: "0"});
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(json);
});
});
});
});
The client side is the following:
$("form[name='manage_notizie']").submit(function(e) {
req="../admin/insert_data"
var tmp_notizia = $( "input[name=notizia]" ).val();
var tmp_id_notizia = $( "input[name=id_notizia]" ).val();
$.ajax({
url: req,
type: "POST",
data: {id_notizia:tmp_id_notizia, notizia:tmp_notizia},
async: false,
success: function (msg) {
location.reload();
},
error: function (msg) {
alert("Errore nel server")
},
cache: false,
});
e.preventDefault();
});
I know that by deafult, if I don't specify any access control allow origin, the server will respond only if the request arrives from itself (host a).
Now, for example if a request comes from www.host-b.com to www.host-a.com/insert_data, my server would not answer to the request (like I want) but it does the computing stuffs (which I don't want)
Am I missing something?

Where is the 'current directory' for node-static?

Here's my server code which is actually the node-static example code!
var static = require('node-static');
//
// Create a node-static server to serve the current directory
//
var file = new(static.Server)('.', { cache: 7200, headers: {'X-Hello':'World!'} });
require('http').createServer(function (request, response) {
request.addListener('end', function () {
//
// Serve files!
//
file.serve(request, response, function (err, res) {
if (err) { // An error as occured
console.error("> Error serving " + request.url + " - " + err.message);
response.writeHead(err.status, err.headers);
response.end();
} else { // The file was served successfully
console.log("> " + request.url + " - " + res.message);
}
});
});
}).listen(8080);
console.log("> node-static is listening on http://127.0.0.1:8080");
So when it says, 'current directory', where does it mean?

Resources