socket.io not working in Chrome - socket.io

i'm trying the this simple socket.io example and it works in Safari (send/receive from both sides). However, in the Chrome the client receives messages but the server won't receive messages sent by the client
index.html
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888');
socket.on('news', function (data) {
console.log(data);
writeMessage(data);
socket.emit('my other event', { my: 'data' });
});
function writeMessage(msg) {
var msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
msgArea.innerHTML = msg.hello;
}
else {
msgArea.innerHTML = msg;
}
}
</script>
</head>
<body>
<div id="msgArea">
</div>
</body>
</html>
server.js
var app = require('http').createServer(handler)
, io = require('/usr/local/lib/node_modules/socket.io').listen(app)
, fs = require('fs')
app.listen(8888);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Am I missing something? Chrome is on v.19

You can use http://socket.io-test.com to see if the problem is with your browser/proxy or your code.

Related

function won`t run in if statement (eventlistener && eventlistener) javascript

I'm trying to get an if statement going to get api results.
First I put eventlisteners(click) on my images and when they are BOTH clicked, the get-api-results function should run.
I know I asked something similar before but I got that one screwed up, with this I`m a little closer I think.
Here`s the code
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img2");
img2.src = "https://picsum.photos/200/300";
const imgCheck = img.addEventListener("click", function(e) {
console.log("check")
})
const img2Check = img2.addEventListener("click", function(e) {
console.log("ok")
})
img.onclick = function () {location.href = "http://localhost:1234/pageTwo.html";};
document.body.appendChild(img);
document.body.appendChild(img2);
if (imgCheck && img2Check){
async function fetchRecipeOne() {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch?query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}}
fetchRecipeOne();
} else {
console.log('no results');
}
And the html pages
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img ><img/>
<script type="module" src="app.js"></script>
</body>
</html>
And page 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<title>Title</title>
</head>
<body>
<img id="img2"><img/>
<script type="module" src="app.js"></script>
</body>
</html>
Again, I`m pretty new to this stuff so if can give me enough details to sort this out you would do me a big favour.
Thanks!
Tom
addEventListener() does not return anything.
Maybe you can create a variable and change it in the eventlistener, like so:
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
});
Also you redirect the user when he click on img, reset the click so to say. Maybe delete that
And the where you define img2 you try to create an element with the name 'img2' which isn't a valid element.
So change:
let img2 = document.createElement("img2");
To:
let img2 = document.createElement("img");
Lastly you check is the user has clicked on both the images when the script runs, what you can do is set the if statement in the async function, and call the function when the user clicks on a img.
So it could look something like:
import axios from 'axios';
const container = document.getElementById('container')
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
let img2 = document.createElement("img");
img2.src = "https://picsum.photos/200/300";
let imgCheck = false;
img.addEventListener("click", function(e) {
imgCheck = true;
fetchRecipeOne();
});
let img2Check = false;
img2.addEventListener("click", function(e) {
img2Check = true;
fetchRecipeOne();
});
document.body.appendChild(img);
document.body.appendChild(img2);
async function fetchRecipeOne() {
if (imgCheck && img2Check) {
try {
const result = await axios.get('https://api.spoonacular.com/recipes/complexSearch? query=pasta&maxFat=25&number=2&apiKey=0b4d29adff5f4b41908e8ef51329fc48', {
headers: {
"Content-Type": "application/json"
}
})
console.log(result);
} catch (e) {
console.error(e);
}
} else {
console.log('no results');
}
}

Why does 'import socket.io' doesn't work for me?

I'm learning Socket.io and practicing the demo tutorial with individual client side script file.
However, it didn't work as expected.
Here is my code.
client side HTML: index.html
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="./app.js"></script>
</body>
</html>
client side JS: app.js
import { io } from "socket.io-client";
var socket = io('http://localhost:3000');
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
server side JS: index.js
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a new user join: ', socket.id);
socket.on('chat message', msg => {
io.emit('chat message', msg);
});
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
After node index to execute my server and open localhost:3000 on my browser, the console.log should tells 'a new user join: xxx', but it didn't.
Is there anything wrong with client side app.js?

complex nodejs url mapping

I need help in url mapping in express.js framework in nodejs.
router.get('/first/:second_param', function(res,req){
//processing second_param and rendering a template,
res.render('first.html');
});
router.get('/first/:second_param/get_items', function(res,req){
//again evaluating second_param and and responding accordingly
res.send(jsonData);
});
Is this kind of routing possible in Express 4.0?
first.html makes a ajax request at url './get_items'
Yes, it is possible to do it with Express 4.0.
Here is an example:
you need to install ejs and express: npm install ejs express
app.js file:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.redirect('/home/2');
});
app.get('/home/:itemId', function(req, res) {
var itemId = req.params.itemId;
console.log(itemId);
res.render('index');
});
app.get('/api/items/:itemId', function(req, res) {
var itemId = req.params.itemId;
console.log('item id: %s', itemId);
res.json([{name: 'item1'}]);
});
app.listen(8080, function() {
console.log('server up and running at 8080');
});
views/index.ejs file:
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Hello World!</h1>
<script>
function responseGET() {
if(this.readyState !== 4 || this.status !== 200) return;
alert(this.responseText);
}
function getItems(URL) {
var request = new XMLHttpRequest();
request.open('GET', URL, true);
request.onreadystatechange = responseGET.bind(request);
request.send(null);
}
function domReady() {
getItems('http://localhost:8080/api/items/1');
}
document.addEventListener('DOMContentLoaded', domReady);
</script>
</body>
</html>
Basically I am have a server which is serving an index.html when someone requests at /home/:itemId and also I am exposing another route for serving items /api/items/:itemId.
From the client side once the DOM is ready I am requesting to /api/items/:itemId some items which then are displayed in the index html.

Marionette events are not triggered on Route

Why Marionette events are not triggered when I access a URL?
When I access the URL it suppose to call the function API.goHome()
but it doesn't! I don't understand why?
Here is my Code:
App.js
var PatientPortal = new Marionette.Application();
PatientPortal.addRegions({
'headerRegion': '#header',
'bodyRegion': '#body',
'footerRegion': '#footer'
});
PatientPortal.on("before:start", function () {
console.log("Started");
});
PatientPortal.navigate = function (route, options) {
options || (options = {});
Backbone.history.navigate(route, options);
};
PatientPortal.getCurrentRoute = function () {
return Backbone.history.fragment
};
PatientPortal.on("start", function(){
if (Backbone.history) {
Backbone.history.start();
}
if(PatientPortal.getCurrentRoute() == ""){
PatientPortal.navigate('home');
}
});
PatientPortal.start();
and Router Code:
PatientPortal.module("Portal", function (Portal, PatientPortal, Backbone, Marionette, $, _) {
Portal.Router = Backbone.Marionette.AppRouter.extend({
controller: "API",
appRoutes: {
"": "goHome",
"home": "goHome"
}
});
var API = {
goHome: function () {
console.log("go home");
}
};
PatientPortal.on("home:route", function () {
console.log("OKOKOK")
API.goHome();
});
PatientPortal.addInitializer(function () {
new Portal.Router({
controller: API
});
});
});
and here a home page code:
<!DOCTYPE html>
<html>
<head>
<title>INSAH - Login Page</title>
</head>
<body>
<div id="header"></div>
<script src="./js/assets/provider/jquery/jquery-2.1.1.min.js"></script>
<script src="./js/assets/provider/underscore/underscore-min.js"></script>
<script src="./js/assets/provider/backbone/backbone-min.js"></script>
<script src="./js/assets/provider/backbone/backbone.babysitter.min.js"></script>
<script src="./js/assets/provider/backbone/backbone.wreqr.min.js"></script>
<script src="./js/assets/provider/marionette/backbone.marionette.min.js"></script>
<script src="./js/app.js"></script>
<script src="./js/routes/route.js"></script>
</body>
</html>
Thanks.
I figured out the problem, it was because of starting the backbone history, the AddInitializer functuion shoudl be as following:
PatientPortal.addInitializer(function () {
new Portal.Router({
controller: API
});
Backbone.history.start();
});
and we should remove this line from app.js:
Backbone.history.start();

How do I post in yammer specific group?

I went through the yammer api's and created an simple html to post the feed into the wall.
But I have not found a clear idea to post to specific group.
I am using the following code to post on the wall.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux/x86 (vers 11 February 2007), see www.w3.org"/>
<title>A Yammer App</title>
<script src="https://assets.yammer.com/platform/yam.js" type="text/javascript">
</script>
<script type="text/javascript">
//<![CDATA[
yam.config({appId: "hyB2pTvrL36Y50py8EWj6A"});
//]]>
</script>
<title>A Yammer App</title>
</head>
<body>
<button onclick='post()'>Post on Yammer!</button>
<script type="text/javascript">
//<![CDATA[
function post() { yam.getLoginStatus( function(response) { if (response.authResponse) { alert(1); yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } else { alert(2); yam.login( function (response) { if (!response.authResponse) { yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } }); } }); }
//]]>
</script>
<script src="https://assets.yammer.com/platform/yam.js" type="text/javascript">
</script>
<script type="text/javascript">
//<![CDATA[
yam.config({appId: "hyB2pTvrL36Y50py8EWj6A"});
//]]>
</script>
<button onclick='post()'>Post on Yammer!</button>
<script type='' "text/javascript">
function post() { yam.getLoginStatus( function(response) { if (response.authResponse) { alert(1); yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } else { alert(2); yam.login( function (response) { if (!response.authResponse) { yam.request( { url: "https://www.yammer.com/api/v1/messages.json" , method: "POST" , data: { "body" : "HelloTest"} , success: function (msg) { alert("Post was Successful!: " + msg); } , error: function (msg) { alert("Post was Unsuccessful..." + msg); } } ); } }); } }); }
</script>
</body>
</html>
Can anyone guide me on this ?
I have changed the application id with the group application id as well.however it's just getting posted in the same wall with from as embed-widget.
you will have to include the group id in the API request to post the message .. here is an example in c#
StringBuilder data = new StringBuilder();
data.Append("body=" + System.Web.HttpUtility.UrlEncode(reply));
// the below line has the group Id encoded into the URL
data.Append("&group_id=" + System.Web.HttpUtility.UrlEncode(groupId));
//Create byte array of the data that is to be sent
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
//Set the content length in the request header
request.ContentLength = byteData.Length;
//write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
JObject jsonObj = null;
//Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
//get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
jsonObj = JObject.Parse(reader.ReadToEnd());
//Console.WriteLine("Message posted successfully!!");
return jsonObj["messages"][0]["id"].ToString();
}
}
This will post message to the particular group.
You should pass the group ID.
<script>
yam.config({appId: "Your App ID"}); //Your APP ID
</script>
<button style="width:150px" onclick='post()'>Post</button>
<script>
function post() {
yam.getLoginStatus( function(response) {
if (response.authResponse) {
yam.request(
{ url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body" : "Posted to the group", "group_id":"UR GROUP ID"} // Pass ur Group ID here
}
);
} else {
yam.login( function (response) {
if (!response.authResponse) {
yam.request(
{ url: "https://www.yammer.com/api/v1/messages.json"
, method: "POST"
, data: { "body" : "Posted to the group", "group_id":"UR GROPU ID"}
}
);
}
});
}
});
}
</script>
I wrote a small API wrapper : Yammer.SimpleAPI.
You can use directly from Nuget

Resources