xmlhttprequest status is always 0 and no response in responseText - node.js

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' : '*'
});

Related

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.

Autobahn - Sent non-empty 'Sec-WebSocket-Protocol' header error

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?

Getting Information From Mongo And Displaying It With AngularJS

Hello I am trying to learn the mean stack and seem to be stuck.
I created a node.js, express angular and mongo project.
I have installed mongo with npm install mongodb
How do I pass data from mongo to the angular view?
my index.ejs file looks like this
<!DOCTYPE html>
<html ng-app="phonecatApp">
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/javascripts/countriesCtrl.js"></script>
<script src="/javascripts/angular.min.js" ></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<div ng-controller="PhoneListCtrl">
<table border="1" cellspacing="0" cellpadding=3>
<tr><td>Abbreviation</td><td>Name</td></tr>
<tr ng-repeat="state in states">
<td>{{state.abbreviation}}</td><td>{{state.name}}</td>
</tr>
</table>
</div>
</body>
</html>
my countriesCtrl.js looks like this
var MongoClient = require('mongodb').MongoClient;
//var mongoClient = new MongoClient(new Server('localhost', 27017));
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope) {
$scope.lkp_states = function() {
MongoClient.connect("mongodb://localhost:27017/website", function(err, db) {
if(err) {
return console.dir(err);
}
else
{
console.log("connected to mongo");
}
})
return db.collection('states');
}
});
The error I get is this
GET http://localhost:3000/ [HTTP/1.1 200 OK 35ms]
Use of getUserData() or setUserData() is deprecated. Use WeakMap or element.dataset instead. requestNotifier.js:63
GET http://localhost:3000/stylesheets/style.css [HTTP/1.1 304 Not Modified 17ms]
GET http://localhost:3000/javascripts/countriesCtrl.js [HTTP/1.1 304 Not Modified 15ms]
GET http://localhost:3000/javascripts/angular.min.js [HTTP/1.1 304 Not Modified 7ms]
ReferenceError: require is not defined countriesCtrl.js:2
http://localhost:3000/javascripts/angular.min.js is being assigned a //# sourceMappingURL, but already has one
Error: [$injector:modulerr] http://errors.angularjs.org/1.2.21/$injector/modulerr?p0=phonecatApp&p1=%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.21%2F%24injector%2Fnomod%3Fp0%3DphonecatApp%0Ay%2F%3C%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A6%3A443%0AZc%2Fb.module%3C%2F%3C%2Fb%5Be%5D%3C%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A20%3A385%0AZc%2Fb.module%3C%2F%3C%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A20%3A273%0Ae%2F%3C%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A33%3A206%0Aq%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A7%3A288%0Ae%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A33%3A148%0Agc%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A36%3A250%0Afc%2Fc%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A18%3A58%0Afc%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A18%3A270%0AXc%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A17%3A369%0A%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A213%3A58%0Aa%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A144%3A399%0Aoe%2Fc%2F%3C%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A31%3A159%0Aq%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A7%3A288%0Aoe%2Fc%40http%3A%2F%2Flocalhost%3A3000%2Fjavascripts%2Fangular.min.js%3A31%3A143%0A angular.min.js:6
GET http://localhost:3000/stylesheets/style.css
The MongoClient uses require.js, which is a common way to include libraries in node.js. In this case, however, you aren't running this code on the server in node.js, you are running it on the client in the browser, and thus don't have require.js defined by default.
You have three options to solve this situation:
Include require.js and register it as a script in your HTML.
Load the MongoClient manually by using a <script> tag in your HTML and using the new MongoClient() function.
Refactor your application to perform the Mongo Database access at the server level in node.js and only have your client HTML perform a request for the query results rather than perform the query itself. (recommended)

Cross origin requests are only supported for HTTP error

i am using xmlhttpRequest to get data from database but it shows an error cross origin request are only supported for http.
i tried "header('Access-Control-Allow-Origin: *');" in php but still it shows error.
here is my html code
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","devangpatel.host56.com/sample.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
nd here is php
<?php
header('Access-Control-Allow-Origin: *');
$con=mysqli_connect("host","user","password","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM demo");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>

Can't find path for socket.io.js

I have my node.js and socket.io setup and running perfectly on my local machine, but now I am trying to transfer it to my live server.
I have installed node.js and socket.io and they're working, but I can't seem to link to the socket.io/socket.io.js file through my client. It keeps coming back with "500 Internal Server Error"
I have tried using both these paths:
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
and
<script type="text/javascript" src="https://localhost:8080/socket.io/socket.io.js"></script>
Why isn't it being found?
"500 Internal Server Error" usually means "server crash" or at least "server encountered an exception". So the problem might not a missing socket.io.js.
Regardless, when I have a discrepancy between local working and remote not working, it's sometimes due to a difference in the environment variables. Where are you deploying your node.js? Heroku, EC2, Joyent?
Have you changed the connection-string? Have you checked with the browser inspector, if the javascript-file is loaded?
var sio = io.connect('http://yourdomain.com:80');
sio.socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
Here i post two files one is chat.js and other is chat.html . This has the path for socket.io.js in html.this works.
1) chat.js :
var io = require("socket.io");
var socket = io.listen(1223);
socket.set("log level", 1);
var people = {};
socket.on("connection", function (client) {
client.on("join", function(name){
people[client.id] = name;
client.emit("update", "You have connected to the server.");
socket.sockets.emit("update", name + " has joined the server.")
socket.sockets.emit("update-people", people);
});
client.on("send", function(msg){
socket.sockets.emit("chat", people[client.id], msg);
});
client.on("disconnect", function(){
socket.sockets.emit("update", people[client.id] + " has left the server.");
delete people[client.id];
socket.sockets.emit("update-people", people);
});
});
2) chat.html :
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://localhost:1223/socket.io/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var socket = io.connect("127.0.0.1:1223");
$("#chat").hide();
$("#name").focus();
$("form").submit(function(event){
event.preventDefault();
});
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#chat").show();
$("#msg").focus();
ready = true;
}
});
$("#name").keypress(function(e){
if(e.which == 13) {
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
ready = true;
$("#login").detach();
$("#chat").show();
$("#msg").focus();
}
}
});
socket.on("update", function(msg) {
if(ready)
$("#msgs").append("<li>" + msg + "</li>");
})
socket.on("update-people", function(people){
if(ready) {
$("#people").empty();
$.each(people, function(clientid, name) {
$('#people').append("<li>" + name + "</li>");
});
}
});
socket.on("chat", function(who, msg){
if(ready) {
$("#msgs").append("<li><strong><span class='text-success'>" + who + "</span></strong> says: " + msg + "</li>");
}
});
socket.on("disconnect", function(){
$("#msgs").append("<li><strong><span class='text-warning'>The server is not available</span></strong></li>");
$("#msg").attr("disabled", "disabled");
$("#send").attr("disabled", "disabled");
});
$("#send").click(function(){
var msg = $("#msg").val();
socket.emit("send", msg);
$("#msg").val("");
});
$("#msg").keypress(function(e){
if(e.which == 13) {
var msg = $("#msg").val();
socket.emit("send", msg);
$("#msg").val("");
}
});
});
</script>
</head>
<body>
<div class="row">
<div class="span2">
<ul id="people" class="unstyled"></ul>
</div>
<div class="span4">
<ul id="msgs" class="unstyled"></ul>
</div>
</div>
<div class="row">
<div class="span5 offset2" id="login">
<form class="form-inline">
<input type="text" class="input-small" placeholder="Your name" id="name">
<input type="button" name="join" id="join" value="Join" class="btn btn-primary">
</form>
</div>
<div class="span5 offset2" id="chat">
<form id="2" class="form-inline">
<input type="text" class="input" placeholder="Your message" id="msg">
<input type="button" name="send" id="send" value="Send" class="btn btn-success">
</form>
</div>
</div>
</body>
</html>
Run chat.js using command - node chat.js
and run chat.html in browser.
I know it's been 8 years old but I faced the same error, maybe my explanation could help someone.
By "trying to transfer to my live server" I did deploying it to virtual shared hosting that is running Node through Passenger module of Apache. Then I contacted the tech support and they said the script is starting to listen some ports and crashes and it is simply not possible on this type of hosting plan, I should apply for VPS/VDS instead.
It sounds strange because the app did not even start to listen, it's just about accessing static files. But probably the way Express is delivering static files is not working. Logs say:
[pid 66771] 19:33:18 listen(12, 511) = -1 EPERM (Operation not permitted)
events.js:183
throw er; // Unhandled 'error' event
^
I was able to read Express is using "stream" (nodejs.org/api/stream.html) to deliver static files and I have a suggestion it is simply not working on that type of hosting. The other static files are existing physically so they are delivered with Nginx and they do not fail. This makes some surprise as some files are loaded and some give error 500, not even 4xx when the resource can't be located.
Basically response 500 tells us the output unexpectedly ended. The logs say "end of script before headers". It is unpleasant when you can't access any log messages and just receive response 500 and have to contact support to see the logs.

Resources