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.
Related
My goal is to display a website which gives users a menu, then from there they click on what functionality they want to run, and then node runs a command on the back end on a ubuntu server using "exec" then displaying the results to the webpage.
So far I have two files, a nodejs file and an html page
var http = require('http'),
exec = require('child_process').exec,
fs = require('fs') ;
function onRequest(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('form.html', function(err, data){
if(err)
{
res.write("err.message");
}
else
{
res.write(data);
res.end();
}
});
}
var server = http.createServer(onRequest);
server.listen(80, '0.0.0.0');
console.log("Server Running");
then the form.html
<!DOCTYPE html>
<html>
<body>
<form>
Please select from the following options:
<select id="mySelect">
<option value="apps">Insert all Apps belonging to a group</option>
<option value="groups">Insert groups in databse</option>
<option value="database">Refresh database group table</option>
<option value="another">Add all app from one group to another</option>
<option value="id">Get Group ID</option>
<option value="user">Get User ID</option>
<option value="list">Get list of all apps</option>
</select>
</form>
<p>Click the button to change the selected fruit to banana.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
if(document.getElementById("mySelect").value = "apps")
{
//do something and display results to webpage
}
else
{
//display error
}
}
</script>
</body>
</html>
My question is, is this the right way of carrying out this task? and if so,should I export the onRequest function which would then allow me to display what I want to the webpage with res.write ?
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' : '*'
});
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.
I'm having trouble getting the now.js chat client tutorial to work. (I've also followed this video almost exactly).
server.coffee:
fs = require 'fs'
http = require 'http'
now = require 'now'
server = http.createServer (req, res) ->
fs.readFile(
'index.html'
(err, data) ->
res.writeHead(
200
'Content-Type': 'text/html'
)
res.end(data)
)
server.listen 8080
everyone = now.initialize(server)
everyone.now.distributeMessage = (msg) ->
everyone.now.receiveMessage(#.now.name, msg)
index.html:
<html>
<head>
<title>nowjs title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/Flotype/now/master/lib/now.js"></script>
<script type="text/javascript">
$(document).ready(function() {
now.name = prompt("What's your name?", "");
now.receiveMessage = function(name, msg) {
return $("<div></div>").text("" + name + ": " + msg).appendTo("#msg");
};
return $("#send-button").click(function() {
now.distributeMessage($("#text-input").val());
return $("#text-input").val("");
});
});
</script>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text-input">
<input type="button" value="Send" id="send-button">
</body>
</html>
When I load up the server with node server.js,
I get an error that says "require not defined" on line 1 of now.js. Consequently, the client side code can't find the variable 'now'.
I understand that 'require' is a node function, but how do I get the client to understand that?
Any help will be appreciated.
The file you're including in your client source (../Flotype/now/master/lib/now.js) is the Node server side code that is included in your node process when calling now = require 'now'.
So changing your included client source file from .../Flotype/now/master/lib/now.js to /nowjs/now.js will fix your problem.
Where does this /nowjs/now.js file come from?
When using NowJS (and many other npm packages that do client/server communication) you extend the server object. This is done with the line everyone = now.initialize(server) (Code Here).
What the initialize function does is wrap your server with the fileServer (Code Here) class in NowJS. This adds a resource under the "folder" nowjs which serves the client now.js file.
I got this error when trying to run nodejs file with js command instead of node.
Eg: if the nodejs file name is test.js, I was doing
js test.js
instead of
node test.js
I hope this helps too for people searching for this error.
I'm trying to work the Redis Cookbook example:
var http = require('http'),
io = require('socket.io')
fs = require('fs'),
redis = require('redis'),
rc = redis.createClient(9189, "pike.redistogo.com");
rc.auth("passwd", function() {
console.log("Connected! to redistogo!");});
rc.on("connect", function() {
rc.subscribe("chat");
console.log("rc connect event");
});
I am successful through here but never get "message."
rc.on("message", function (channel, message) {
console.log("Sending: " + message);
socketio.sockets.emit('message', message);
});
webpage = http.createServer(function(req, res){
console.log('webpage request starting...');
fs.readFile('./index.htm', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
webpage.listen(7777);
my client side index.htm is this
<!docttype html>
<html lang="en">
<head>
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"> </script>
<script src="http://www.heaphash.com:7777/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('www.heaphash.com', { port: 7777});
socket.on('message', function(data){
var li = new Element('li').insert(data);
$('messages').insert({top: li});
}
</script>
<meta charset="utf-8">
<title>Chat with Redis</title>
</head>
<body>
<ul id="messages">
<!-- chat messages go here -->
</ul>
<form id="chatform" action="">
<input id="chattext" type="text" value="" />
<input type="submit" value="Send" />
</form>
<script>
$('#chatform').submit(function(){
socket.emit('message', $('chattext').val());
$('chattext').val(""); //cleanup the field
return false;
});
</script>
</body>
</html>
how does a client publish to a specific Redis "chat" channel.
If you are using redis pub/sub functionality within your node.js program you should dedicate one redis client connection for listening on some channel and second redis client connection for sending normal commands and/or publishing messages to your channel(s). From node_redis docs:
When a client issues a SUBSCRIBE or PSUBSCRIBE, that connection is put
into "pub/sub" mode. At that point, only commands that modify the
subscription set are valid. When the subscription set is empty, the
connection is put back into regular mode.
If you need to send regular commands to Redis while in pub/sub mode,
just open another connection.
Your problem is also related to these questions:
Redis / Node.js - 2 clients (1 pub/sub) causing issues with writes
Why can't I have a single Redis client acting as PUB and Sub in the same connection?
I believe that the example from that book is missing something, I also read that book and wondered. You are subscribed to the Redis channel and are waiting for messages on the server side, but you never publish to that channel. What is missing is an event listener so when there is a websocket message, you publish that message to the redis channel.