getting error in <script src = "/socket.io/socket.io.js"></script> - javascript

i know this question has been asked many times buit i have spent 3 hours trying to figure it out but to no avail. i am getting error in GET
http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED
and io is not defined. any help would be highly appreciated. i am typing extra coz my post requires more details ..........
public/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="styles.css" />
</head>
<body>
<div id="wrapper">
<div class="form_div" id ="login">
<p class="form_label">LOGIN FORM</p>
<form method="post" action="">
<p><input id ="user-name" type="text" placeholder="Enter user-name"></p>
<p><input id = "pass-word" type="password" placeholder="**********"></p>
<p><input id = "submit" type="submit" value="LOGIN"></p>
</form>
</div>
<br>
<br>
<br>
<div class="form_div" id = "signup">
<p class="form_label">SIGNUP FORM</p>
<form method="post" action="">
<p><input id ="signupusername" type="text" placeholder="Enter
Name"></p>
<p><input id = "signuppass" type="password"
placeholder="**********"></p>
<p><input id ="register" type="submit" value="SIGNUP"></p>
</form>
</div>
</div>
<script src = "index.js"></script>
<script src = "/socket.io/socket.io.js"></script>
public/index.js
var socket = io();
var loginDiv = document.getElementById('login');
var Username = document.getElementById('user-name');
var loginPassword = document.getElementById('pass-word');
var login = document.getElementById('submit');
var SignUpDiv = document.getElementById('signup');
var Signupuser = document.getElementById('signupusername');
var Signuppass = document.getElementById('signuppass');
var signup = document.getElementById('register');
login.onclick = function(){
socket.emit('login-details',{
username:Username.value,
password:loginPassword.value
});
}
signup.onclick = function(){
socket.emit('signup-details',{
newuser:Signupuser.value,
newuserpassword:Signuppass.val
});
}
socket.on('login-response',(data)=>{
if(data.success){
alert('login Successful');
}
else{
alert('login Unsuccessful');
}
});
socket.on('signup-response',(data)=>{
if(data.success){
alert('Signup Successful')
}
else{
alert('Signup-Successful')
}
});
server/server.js
var express = require('express');
var path = require('path');
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
const socketIO = require('socket.io');
var app = express();
var server = http.createServer(app);
const port = process.env.PORT ||3000;
var io = socketIO(server);
const pathjoin = path.join( __dirname ,'../public');
app.use(express.static(pathjoin));
MongoClient.connect('mongodb://localhost:27017/DETAILS',(err,client)=>{
if(err){
return console.log('unable to connect to the MongoDb server');
}
const db =client.db('DETAILS');
console.log('connected to the MongoDb server');
});
io.on('connection',(socket)=>{
console.log('new user connected');
//login
socket.on('login-details',(data)=>{
db.collection('user-
details').find({username:data.username,password:data.password},
(err,result)=>{
if(err) throw err;
socket.emit('login-response',{
success:true
});
});
});
//signup
socket.on('signup-details',(data)=>{
db.collection('user-
details').insert({username:data.newuser,password:data.newuserpassword},
(err,result)=>{
if(err) throw err;
socket.emit('signup-response',{
success:true
});
});
});
});
app.listen(port,()=>{
console.log('server started');
});

In your server/server.js, at the very end of your codes, change app.listen() to server.listen(), because express requires that you instantiate a HTTP server in Socket.IO.
This should be your new ending part of server.js
server.listen(port,()=>{
console.log('server started');
});

In index.html
<script src = "index.js"></script>
<script src = "/socket.io/socket.io.js"></script>
change it to
<script src = "/socket.io/socket.io.js"></script>
<script src = "index.js"></script>
Swap the includes in html .First you need to include socket.io and then use it in index.js.
In index.js
var socket = io.connect();

error solved. It was a silly mistake! since socket.io uses http server and not the express server. so i did create a http server but at during listening to a port i use express like app.listen(). In server/server.js it should be:
server.listen(port,()=>{ console.log('server started');});

Try this. Change,
<script src = "/socket.io/socket.io.js"></script>
to
<script src="http://YOUR_IP_ADDRESS/socket.io/socket.io.js"></script>

Related

Displaying output of console.log to HTML in Node.js debugging

I've been having this issue for the past 6 or so hours and I can't figure it out. I followed examples perfectly, yet when I run my server, the console.log output does not get displayed on the html page. This is my first time messing with Node.js. Here is the code:
Server:
require('dotenv').config()
var Twitter = require ('twitter');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io').listen(app);
var port = process.env.PORT || 8000;
var express = require ('express');
var events = require('events')
var eventEmitter = new events.EventEmitter();
// add API keys to .env file. .env_sample for details
var T = new Twitter({
consumer_key: process.env.CONSUMER_KEY,
consumer_secret: process.env.CONSUMER_SECRET,
access_token_key: process.env.ACCESS_TOKEN_KEY,
access_token_secret: process.env.ACCESS_TOKEN_SECRET
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static(__dirname + '/public'));
eventEmitter.on('logging', function(message) {
io.emit('log_message', message);
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
// Override console.log
var originConsoleLog = console.log;
console.log = function(data) {
eventEmitter.emit('logging', data);
originConsoleLog(data);
};
// code for test.
setInterval(function() {
console.log('X: ' + Math.random());
}, 2000);
/*T.get('statuses/home_timeline', function(error, tweets, response) {
if(error) throw error;
tweets.render
console.log(tweets); // General Tweet Timeline
});*/
HTML:
<!doctype html>
<html lang = "eng">
<head>
<meta charset="UTF-8">
<title> Twitter Client</title>
<link rel="stylesheet" type = "text/css" href="/css/index.css">
</head>
<body>
<img class="logo" src="/images/Twitter_Logo_Blue.png" height = "250" width = "250" alt="blue_bird">
<h1> Using this simple twitter client, the user can view general tweets, specify a specific twitter handle, and search tweets by text. </h1>
<ul id = "messages"></ul>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function(){
var socket = io();
socket.on('log_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
For the life of me I can't figure out what's going on, and this project is due shortly. Any help would be GREATLY appreciated.

socket io not giving the desired output

I have created a index.js which loads index.html using sockets.
the server is running successfully and also the index.html page loads. but cant append the written text in the div.
index.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000, function() {
console.log("SERVER CREATED WITH PORT 3000");
});
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket) {
socket.on('send', function(data) {
io.sockets.emit('new', data);
});
});
index.html
<html>
<head>
<title>chat</title>
<style>
#chat {
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input id="message" />
<input type="submit" />
</form>
<h1>Working</h1>
<script src="jquery-3.2.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($) {
var socket = io.connect();
var $messageform = $('#send-message');
var $messagebox = $('#message');
var $chat = $('#chat');
$messageform.submit(function(e) {
e.preventDefault();
socket.emit('send', $messagebox.val());
$messagebox.val('');
});
socket.on('new', function(data) {
$chat.append(data + "<br />");
});
});
</script>
</body>
</html>
These are the files which I have created and want to send the text to all tabs.
The browser just gets refreshed without loading the text when submit is hit.
Please let me know what I am doing wrong.

Socket.emit not going through

index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.

Get data by socket.io in html page

I have read a lot of tutorial, and sample code to send data from a node.js class to an html page and show this data.
such as link1, link2,link3,link4,link5
and some others.
I am getting some data from UDP listener and need to send it after some processing to an html page to show it. here is my code:
The udp receiver:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
var http = require('http'),
dgram = require('dgram'),
socketio = require('socket.io'),
fs = require('fs');
var html = fs.readFileSync(__dirname + '/html/showMap.html');
var app = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(html);
io.sockets.emit('welcome', { message: 'Welcome!'});
}).listen( server_port, server_ip_address, function() {
console.log('Listening');
});
var io = socketio.listen(app),
socket = dgram.createSocket('udp4');
socket.on('message', function(content, rinfo) {
console.log('got message', content, 'from', rinfo.address, rinfo.port);
io.sockets.emit('udp message', 'content' /*content.toString()*/);
});
socket.bind(5001);
and my html page which is called 'showMap.html'
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost', {port: 8080});
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";​
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>
but by sending packet, html page has not changed.
Here is my console log of running code:
Atis-MacBook-Pro:startWithNode muser$ npm start
StartWithNodejs#1.0.0 start /Volumes/Project/Project/NodeJS/startWithNode
node index.js
Listening got message from 127.0.0.1 64047
What is wrong in my code?
I tested this locally. In your HTML file I made two changes and it worked.
1 - Replace io.connect('localhost', {port: 8080}); with io.connect('localhost:8080');
2 - There was a strange \u200b character at the end of the document.getElementById("date").innerHTML = "My new text!"; line. I deleted that and ended up with:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost:8080');
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>
Which replaces the content of results.
in this example you will be able to get JSON data from php file and send it to all connected clients.
RunThisFileThroughNodeJs.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
var request = require("request")
var url = "http://localhost/api/index.php";
events = require('events'),
serverEmitter = new events.EventEmitter();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
setInterval(
function(){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
io.emit('chat message', body);
}
});
},5000);
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
Don't Forget to install express , request for nodejs
Now make this file i will call it index.html so the response of my file will be here.
index.html
<!doctype html>
<html>
<head>
<title>Prices API</title>
<script src="http://localhost/js/socket.io.js"></script>
</head>
<body>
<div id="price_list"></div>
<script>
var socket = io();
socket.on('chat message', function(msg){
document.getElementById("price_list").innerHTML = JSON.stringify(msg);
console.log(msg);
});
</script>
</body>
</html>

Cant get response making real time chat with nodejs

I'm trying to make real time chat with nodeJs.. But i have some problems.
The console.log in the part of
io.on('connection', function(socket)
{
console.log("A user connected");
});
does not console.log at all.
When I got stuck i was searching for a guide.. I build it almost the same as in the guide.
Here is my html page:
<!doctype html>
<html>
<head>
<title>
Socket.IO chat
</title>
<link rel="stylesheet" href="./CSS/style.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
<ul id="messages">
</ul>
<form action="">
<input id="m" autocomplete="off" />
<button>
Send
</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
And here my js file:
var app = require("express")(),
http = require("http").Server(app),
io = require("socket.io")(http),
port = 3000;
app.get('/', function(req, res)
{
res.sendFile(__dirname + "./index.html");
});
io.on('connection', function(socket)
{
console.log("A user connected");
});
http.listen(port, function()
{
console.log('Listening on port: ' + port);
});
my file structure:
^because I think it has something to do with the linking between the pages.
I am using this guide: http://socket.io/get-started/chat/
Thanks in advance,
I hope to get some answers so i can go on with this :)
Cheers
It looks like your HTML page is missing the server URL:
var socket = io.connect("http://" + window.location.host); //e.g. http://localhost:3000

Categories