Node JS communicating through sockets - html

I'm trying to play around with sockets. I created a web server in node:
var http = require("http");
var server = http.createServer(function(req,res){
console.log("server has been created");
res.writeHead(200,{"Content-type:": "text/plain"});
res.end("Welcome to my supa' nodejs app");
}).listen(1337);
console.log("Server running at 127.0.0.1:1337");
var io = require("socket.io").listen(server);
io.sockets.on("connection", function(socket){
socket.on("input_written",function(){
console.log("someone clicked the button");
});
});
I also have a html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html lang="en">
<head>
<title>Home page</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost:1337");
function clickedButton()
{
socket.on("connect",function(){
socket.emit("input_written");
});
}
</script>
<button type="button" onclick="clickedButton()">Click me</button>
</body>
</html>
What I'm trying to achieve is when I press that button my console logs "someone clicked the button". However at the moment nothing happens. I'm not sure what I'm missing
UPDATE
As #Zub recommended I added
console.log("clicked");
right before the socket.emit();
I checked the console and this is the output:
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined (index):11
Uncaught TypeError: Cannot call method 'on' of undefined

Since you bind node server on 1337, you have to point that port when you load socket.io.js script.
So try to replace
<script src="/socket.io/socket.io.js"></script>
with
<script src="http://localhost:1337/socket.io/socket.io.js"></script>
Edit
You should also initialize client socket.io connection beyond clickedButton function and leave just socket.emit("input_written"); in it.

The url in your browser needs to match the socket connection url. You have localhost in your io.connect, so make sure the url in your browser reads http://localhost/. If you connect to http://127.0.0.1/ in your browser then it won't work.

Related

XHR works on localhost server but not on my static IP on IIS

I am using IIS on my Windows Server 2012 R2 program. I have a static IP, and I've binded it to a port and enabled port forwarding so it is accessible online. Here's the thing, on localhost my XHR request produces the desired output. But when I search my static IP in the URL, and attempt the request, it does not produce anything. Here are the files:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get.txt", true);
xhttp.send();
}
</script>
</body>
</html>
And here's my desired output "demo_get.txt":
<p>This Content was requested using the GET method.</p>
So can someone please guide me in making my XHR request functional when I enter my Static IP into the url? Thanks.
As suggested by others, I went into the Developer Tools and found that no request was being sent on the Network Tab. So, I investigated my security settings on my local intranet. I enabled some settings, and that's all it took for the XHR requests to function. Thank you everyone for your input!

atom-live-server - resource not found error

Installed atom-live-server using atom IDE
Using atom IDE, launching atom-live-server for an html page,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Classes</title>
</head>
<body>
<script src="code.js"></script>
</body>
</html>
where code.js is,
var Greeter = /** #class */ (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
}());
var greeter = new Greeter("world");
console.log(greeter.greeting);
gives below error in console,
Live reload enabled.
Failed to load resource: `http://127.0.0.1:3000/favicon.ico` the server responded with a status of 404 (Not Found)
Why live-reload server searching for resource favicon.ico?
Just Install "npm install -g live-server" into cmd . then goto your project like cd your project folder name. then run the command "live-server" into cmd. it will automatically open the browser and make your project live reload. No need to atom-live-server or any editor live-reload. Because sometimes atom-live-server doesn't work properly. I personally use it all of my projects. You can try it.

Hit URL in local VM machine via AJAX/REST

I am new to API methodology so sorry for asking such silly question which it may be.I am running Windows 10 on my machine and have setup a Ubuntu VM on Oracle VM VirtualBox. I want to hit the url in AJAX/REST way to get the JSON.I am able to get that JSON data in browser when I am hitting the url within VM environment. How can I accomplish the same via desktop?
I am running a separate server utility on VM which accepts the following url
localhost:8998/sessions
and it provides me data in form of JSON.
I have written the following code with help of W3Schools.
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "192.168.56.780:8998/sessions", true);
xhttp.send();
}
</script>
</body>
</html>
This should return json file in output in the same way as that when I run in browser in VM environment but no output is there on it in specified section.
UPDATE:
I have made changes in "Network" settings of VM making Adapter 2 as below and started the image:
Now I am able to putty it through new IP address 192.168.56.780 assigned automatically by it.Will this solve the above problem.

How to make Web page to not wait for a response after sending a GET request

I am trying to make this web site that resides in Google Drive control a LED(on/off) via esp8266 and arduino. Partially i've succeded in doing what i want by sending to the IP of the module that communicates with the arduino a GET request witch parses it and acts accordingly. ie GET /?LED1=on HTTP/1.1
Problem is that whenever i press a button in the web site it sends the GET request and then it waits for a response from the other end (arduino),and the browser keeps loading until eather I close the connection from the arduino or I reply something like HTTP/1.1 200 OK and then close the conection.
In the first case browser shows the message that was unable to load the page and in second case it simply shows a blank page.
<DOCTYPE html>
<html>
<head>
<title>LED Control</title>
</head>
<body>
<button>LED 1 On</button>
</body>
</html>
I just want to send that LED1=on string somehow without causing the page attempt to load anything back.
A reusable solution
Modify your HTML to be something like this:
<button class="get" data-url="http://78.87.xxx.xx:333/?LED1=on">LED 1 On</button>
Now add this JavaScript:
window.onload = function () {
Array.prototype.forEach.call(document.querySelectorAll('.get'), function(el) {
el.onclick = function () {
// Use this trick to perform CORS requests too
var req = new Image();
req.src = this.dataset.url;
// The following 7 lines are completely optional
req.onload = function () {
// Was successful
};
req.onerror = function (error) {
// Encountered an error
alert('An error occurred while performing the request. + ' error);
};
};
});
};
Now any element with the class "get" when clicked, will send a request to the URL. This won't change the page either. If

WebSocket API Connection issue

I suppose I'm havin' a beginner's problem regarding websocket connection.
Here's the thing, I'm researching on using websocket and I followed this code:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://172.16.0.195:8080/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
... which I copied from the internet. When I tested it, Firefox said that my browser supports websocket feature but it DOESN'T ESTABLISH CONNECTION TO MY SERVER. I try to telnet our server in port 80 and I could gain connection to it. But if I am to use websocket connection in my page,it does not establish connection anymore.
Thank you very much in advance for any inputs/help.
[EDIT]
** by the way, does ".../echo" in my specified websocket connection has to do something with it? I mean, do I have to have some echo.php in my server?
This tutorial helped me a lot:
Getting started with HTML5′s Web Sockets
Now I have my server set up already.