Autobahn - Sent non-empty 'Sec-WebSocket-Protocol' header error - node.js

I am trying to build a WAMP server using NodeJS, wamp.io, and websocket.io.
Here is the server-side code :
var wsio = require('websocket.io');
var wamp = require('wamp.io');
var socketServer = wsio.listen(9000);
var wampServer = wamp.attach(socketServer);
And I am trying to test the pub-sub via browser using AutobahnJS. Here is the client-side code :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wamp Example</title>
</head>
<body>
<ul class="pages">
<li>
<button id="socket">Call</button>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min.jgz">
</script>
<script>
AUTOBAHN_DEBUG = true;
</script>
<script>
var connection = new autobahn.Connection({
url: 'ws://localhost:9000/',
realm: 'realm1'
});
console.log(connection);
connection.onopen = function (session) {
console.log(session);
// session is an instance of autobahn.Session
};
connection.onclose = function(reason, detail){
console.log(reason);
}
connection.open();
</script>
</body>
</html>
But the connection always got this error :
WebSocket connection to 'ws://localhost:9000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
This part of code return 'unreachable'
connection.onclose = function(reason, detail){
console.log(reason);
}
Is there any code I missed?

Related

xmlhttprequest status is always 0 and no response in responseText

I have written a simple node.js server and and ajax request to send and recieve request respectively. Despite of every change made its not working.this is my node.js server code...
var express=require('express');
var server=express();
server.get('/sampleResponse',function(req,res){
if(req.method=="POST"){
console.log('reache`enter code here`d post');
res.status(200).send('connection successful');
}else if(req.method=="GET"){
console.log('reached get');
res.status(200).send('connection successful');
}
});
server.listen('8001','127.0.0.1');
//////below is my html page... running on localhost:8100
<html>
<head>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script>
function submitLoginDetails(){
var JSONLoginObj={rollNo:document.getElementById("rollNo").value,
password:document.getElementById("password").value};
///////////////////////////////////////////////////////////////
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
var xhrdata = "";
if(xhttp.readyState == 4){
if(xhttp.status == 200)
alert(xhttp.responseText);
else
alert(xhttp.status);
}
};
xhttp.open("GET", "http://localhost:8001/sampleResponse", false);
xhttp.send();
}
</script>
</head>
<body>
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Login Page</h1>
</ion-header-bar>
<ion-content>
<form>
Roll Number:<br><br>
<input type="text" id="rollNo"><br><br>
Password:<br><br>
<input type="text" id="password"><br><br>
<button id="loginButton" onclick="submitLoginDetails();">Login</button>
</form>
<p id="demo"></p>
</ion-content>
</ion-pane>
</body>
</html>
when access the same page by clicking on link i get response but no response in xhttp.responseText.
This is a cross domain issue (CORS) which means you are trying to make a request (for a resource) from outside of your current domain. You need to allow set the Access-Control-Allow-Origin to accept all your requests.
You can do this by adding the below lines to your .js file (where you have your express.js code)
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*'
});

How can I deploy the auth0 app to bluemix

I am using a sample project from auth0.com to customize the login page for my app and enable social media login. However I encounter some problem when I try to deploy it to bluemix.
The video tutorial I follow is https://www.youtube.com/watch?v=sHhNoV-sS_I&t=559s
however the sample project is a little bit different from the one in video. It required the command "npm serve" to run it. When I push my project using cf push it shows noappdecked. How can I deploy my project to bluemix?
the app.js code and html code is like
<!DOCTYPE html>
<html>
<head>
<title>Auth0-VanillaJS</title>
<meta charset="utf-8">
<!-- Auth0 lock script -->
<script src="//cdn.auth0.com/js/lock/10.3.0/lock.min.js"></script>
<script src="auth0-variables.js"></script>
<script src="app.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<img alt="avatar" id="avatar" style="display:none;">
<p>Welcome <span id="nickname"></span></p>
<button type="submit" id="btn-login">Sign In</button>
<button type="submit" id="btn-logout" style="display:none;">Sign Out</button>
</body>
window.addEventListener('load', function() {
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN);
// buttons
var btn_login = document.getElementById('btn-login');
var btn_logout = document.getElementById('btn-logout');
btn_login.addEventListener('click', function() {
lock.show();
});
btn_logout.addEventListener('click', function() {
logout();
});
lock.on("authenticated", function(authResult) {
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
// Handle error
return;
}
localStorage.setItem('id_token', authResult.idToken);
// Display user information
show_profile_info(profile);
});
});
//retrieve the profile:
var retrieve_profile = function() {
var id_token = localStorage.getItem('id_token');
if (id_token) {
lock.getProfile(id_token, function (err, profile) {
if (err) {
return alert('There was an error getting the profile: ' + err.message);
}
// Display user information
show_profile_info(profile);
});
}
};
var show_profile_info = function(profile) {
var avatar = document.getElementById('avatar');
document.getElementById('nickname').textContent = profile.nickname;
btn_login.style.display = "none";
avatar.src = profile.picture;
avatar.style.display = "block";
btn_logout.style.display = "block";
};
var logout = function() {
localStorage.removeItem('id_token');
window.location.href = "/";
};
retrieve_profile();
});
You would use the package.json method documented at https://console.ng.bluemix.net/docs/runtimes/nodejs/index.html#nodejs_runtime , first to declare the serve package as one of your dependencies, then to indicate what the scripts.start script should do (which is run npm serve). You can use npm init (https://docs.npmjs.com/cli/init) to create a starting package.json file if you don't already have one.

NodeJS Express | ReactJS component causes timeout error while testing a view using Mocha and ZombieJS

I have added to my Node ExpressJS app some components in ReactJS. Since I introduced these components, my tests are failing due to timeout error.
My test suites is including mocha, zombie, chai and sinon, but the first two are enough to reproduce the error.
This is the test:
// tests/home-tests.js
process.env.NODE_ENV = 'test';
var app = require('../index.js');
var Browser = require('zombie');
describe('Homepage Tests', function() {
before(function(){
server = app.listen(3002);
browser = new Browser({ site: 'http://localhost:3002' });
})
it('should render title', function(done){
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
after(function(done) {
server.close(done);
});
});
This is the layout:
// views/layouts/main.handlebars
<!doctype html>
<!--[if IE 8]> <html class="ie ie8"> <![endif]-->
<!--[if IE 9]> <html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Zombie ReactJS Test!</title>
{{{_sections.page_stylesheets}}}
</head>
<body>
{{{body}}}
{{{_sections.page_javascripts}}}
</body>
</html>
This is the view I want to test:
<h1>A test page for ReactJS</h1>
<div id="example"></div>
{{#section 'page_stylesheets'}}
<!-- ReactJS -->
<script src="https://npmcdn.com/react#15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.1/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
{{/section}}
{{#section 'page_javascripts'}}
<script type="text/babel">
ReactDOM.render(
<p>Hello, world!</p>,
document.getElementById('example')
);
</script>
{{/section}}
I have reproduced the error in this small repo.
It seems that it could be easily fixed with a timeout like it follows:
// tests/home-tests.js
// ...
it('should render title', function(done){
this.timeout(5000);
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
However, this doesn't appear to be the most suitable solution. In particular, would you be able to suggest a way to run test only after the page is fully loaded (without timeouts to be set)?
Thank you in advance

Node.js how to get http message (request, response) from net server (tcp server)?

I have the following code :
var net = require('net');
var fs = require('fs');
var path = require('path');
path = path.join(__dirname, 'index.html');
var fileAsAstream = fs.createReadStream(path);
var server = net.createServer(function (socket) {
socket.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 10\r\n\r\n");
fileAsAstream.pipe(socket);
console.log("server is up. port 8081");
});
server.listen(8081);
index.html
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
(1) Why does chrome make two connections to the server when I try http://localhost:8081 ? How can I make it work with one connection? And how I can format the html file in the browser during this tcp server.
or if there is something that can help me.
(2) It just reads the html file one time when I try to make two connections at telnet.
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 10
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Connection to host lost.

Client disconnects immediately after connection to Node js TCP server

This is my first time with node js. I am trying to get the client to connect to the server and maintain the connection without closure.
This is all hosted in an ubuntu server edition hosted in a virtualbox.
I had checked that the server is actually listening to the port 5000 using
netstat -ant
Websockets is also available on my browser.
I get the following output with error
Echo server dot come
192.168.1.107
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: EPIPE, Broken pipe
at Socket._writeImpl (net.js:159:14)
at Socket._writeOut (net.js:450:25)
at Socket.write (net.js:377:17)
at Socket.ondata (stream.js:36:26)
at Socket.emit (events.js:81:20)
at Socket._onReadable (net.js:678:14)
at IOWatcher.onReadable [as callback] (net.js:177:10)
and if i call socket.end() on the server on connection event handler i get a disconnecting client. My question is how to establish a stable connection using this code, what do i have to change or i am doing wrong here? pulling my hair out - thanks in advance!
HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test RS Server (built over nodejs)</title>
<link rel="stylesheet" href="style.css"></link>
<script src="jquery.min.js" ></script>
<script src="client.js" ></script>
</head>
<body>
<label>Message</label>
<input type="text" id="message_box"></input>
<input type="button" id="submit_btn" value="Send"></input>
<div style="clear:both;"/>
<label>Output</label>
<textarea rows="10" cols="100" id="output_box"></textarea>
</body>
</html>
CLIENT JS
var message_box;
var output_box;
var submit_btn;
var url = "wss://192.168.1.107:5000";
var socket;
function createListeners() {
if ("WebSocket" in window) {
output_box.html("Supports sockets.");
socket= new WebSocket(url);
socket.onopen= function() {
socket.send("con opened");
output_box.html("Connection opened.");
};
socket.onmessage= function(response) {
// alert('got reply '+s);
console.log(response);
output_box.html(response);
};
socket.onclose = function() {
// websocket is closed.
output_box.html("Connection is closed...");
};
submit_btn.click(function(e) {
socket.send(message_box.val());
});
} else {
output_box.html("doesnt support sockets");
};
};
$(document).ready(function() {
message_box = $("#message_box");
output_box = $("#output_box");
submit_btn = $("#submit_btn");
createListeners();
});
SERVER JS CODE
var net = require('net');
var server = net.createServer(function (socket) {
socket.write('server says this\r\n');
socket.pipe(socket);
});
server.on('connection', function(socket) {
socket.write("Echo server dot come\r\n"+socket.address().address);
console.log("Echo server dot come\r\n"+socket.address().address);
// socket.end();
socket.pipe(socket);
});
server.listen(5000);
You are trying to use WebScoket client with simple TCP server. This is a different protocols. You need to setup WebSocket server to make it work. You can use websocket module to do that. Look at the server example code here.

Resources