I am trying to send some json object from the server side to the client side.
var express = require('express');
var app = express();
var server = app.listen(1337);
var io = require('socket.io').listen(server);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function(json) {
io.send('message', json);
});
app.listen(3000);
and on index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data) {
console.log(data);
});
</script>
</body>
</html>
I keep getting this error
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?
EIO=2&transport=polling&t=1602487581123-0' from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Use "socket.io": "^2.3.0", for server side, change server side code to following:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var json = {
var1: 1,
var2: 2,
var3: 3,
};
io.on('connection', function() {
io.send('message', json);
});
http.listen(3000, () => console.log('HTTP server is listening on port 3000'));
For the CORS header, any origins being allowed by default.
And I recommend you use the latest version of socket.io for the client-side. You can use this CDN.
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function(data, json) {
console.log(data, json);
});
</script>
</body>
</html>
Create HTTP Server for client-side:
☁ 64313396 [master] ⚡ http-server -p 3001
Starting up http-server, serving ./public
Available on:
http://127.0.0.1:3001
http://172.31.160.227:3001
http://10.23.128.81:3001
The output of browser console:
Related
I have below folder structure in VS2015:
The server.js has below code:
var express = require('express')
var app = express();
var http = require('http').Server(app);
var path = require('path');
var port = process.env.port || 1337;
app.use(express.static(__dirname + 'client'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,'client', 'HTML1.html'));
});
http.listen(port, function () {
console.log(`listning on ${port}`);
})
and Html1.Html has below code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="imageLoaderApp">
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
</div>
<script src="/client/scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope) {
console.log(`i'm here.'`);
});
</script>
</body>
</html>
When I'm hitting below url in browser
http://localhost:1337/
I'm getting below error in console:
This is happening with all the js files. I even tried to move the html and js files in main folder still getting the same error.
What am I doing wrong?
It looks like HTML1.html is in the client folder. If that is the case I think you need to put the path to the js relative to it so: 'src="scripts/angular.js"'
I have a web service and a node project with a html page. I want to sends get request from my node project to my web service and in the return of web service i want to print that "hello world" on my website.
My web service.
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello World";
}
}
My Node project:
var express=require('express');
var http = require('http');
var https = require("https");
var request=require("request");
var app=express();
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});
app.get('/this',function(req,res){
request
.get('http://localhost:8080/ConnectingToNode/webapi/myresource')
.on('response', function(response) {
console.log(response.statusCode); // 200
console.log(response.headers['content-type']);
var a=response.toString();
console.log(a);
});
});
module.exports = app;
My index.html
<!DOCTYPE html>
<html>
<head>
<title>TO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
function This(){
window.open("http://localhost:8080/ConnectingToNode/webapi/myresource");
}
</script>
<button onclick="This()" type="button">Click Me!</button>
</body>
</html>
I have an instant messaging chat application in the making, and am having problems getting my client to receive data from my server. Could anyone explain to me why this is happening?
app.js
var http = require("http");
var express = require("express");
var socket = require("socket.io");
var app = express();
app.use(express.static(__dirname + "/public"));
var server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on("connection", function(client) {
client.on("join", function(name) {
client.set("nickname", name);
console.log(name + " connected."); // logs name correctly
client.broadcast.emit("names", name);
});
});
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var server = io.connect("http://localhost:8080");
server.on("connect", function(data) {
nickname = "";
while (nickname == null || nickname.trim() == "") {
nickname = prompt("Enter name");
}
server.emit("join", nickname);
});
server.on("names", function(data) {
document.getElementById("txtNames").value = data;
});
</script>
</head>
<body>
<textarea id="txtNames"></textarea>
</body>
</html>
Do you know what a broadcast is? When you broadcast a message as a result of an event from a socket, The message is emitted to all connected clients except for the socket who triggered the event. Same is your case. If you want to emit names event to your connected client then use
socket.emit("names", name); in your app.js
I’m having a problem getting started with Node.js.
I’ve created a basic server that I know works, because if I navigate to http://localhost:5000 in my browser I get the expected message. However, I’m having trouble then connecting to this server on the client side with a basic HTML page.
My Node.js app looks like this:
var http = require('http');
var socket = require('socket.io');
var port = process.env.PORT || 5000;
var players;
var app = http.createServer(function(request, response) {
response.write('Server listening to port: ' + port);
response.end();
}).listen(port);
var io = socket.listen(app);
function init() {
io.configure(function() {
io.set('transports', [ 'xhr-polling' ]);
io.set('polling duration', 10);
});
io.sockets.on('connection', onSocketConnection);
};
function onSocketConnection(client) {
console.log('New connection');
console.log(client);
};
init();
My HTML page looks like this (based on https://github.com/mongolab/tractorpush-server/blob/master/index.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/');
socket.on('all', function(data) {
console.log(data);
});
socket.on('complex', function(data) {
console.log(data);
});
</script>
</body>
</html>
I understand that the sockets.io.js file is automatically generated by socket.io, but I just get the following error when I view my index.html file:
Uncaught ReferenceError: io is not defined
How do I actually connect to my server?
I have created a small server for communication using node.js and socket io
Server:
var express = require('/usr/local/lib/node_modules/express')
var io = require('/usr/local/lib/node_modules/socket.io');
var server = express.createServer();
server.listen(8888,'localhost');
io = io.listen(server);
io.of("namespace").on('connection', function(client){
client.emit("message",'connection successful');
client.on('message', function(m){
console.log("received message"+m);
client.broadcast(m);
});
});
Client:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Comet Test</title>
<script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script>
</head>
<body>
<p><a id='customAlert' href="#" onclick='sendMessage("customAlert")'>publish customAlert</a></p>
<p><a id='customAlert2' href="#" onclick='sendMessage("customAlert2")'>publish customAl
<script type="text/javascript">
// Start the socket
var socket = io.connect('http://localhost:8888/namespace');
socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
socket.on('message', function(msg){
console.log(msg);
});
function sendMessage(m) {
console.log("sending message"+m);
socket.emit("message",m);
}
</script>
</body>
Communication does not happen, am I doing something wrong here?
If your server is listening on port 8888, you need the client to connect to the server on port 8888.
The following line in your client code:
var socket = io.connect('http://localhost/namespace');
Should read:
var socket = io.connect('http://localhost:8888/namespace');