M
M
Mors Clamor2019-05-23 17:40:31
Node.js
Mors Clamor, 2019-05-23 17:40:31

How to initialize socket.io on the client side?

Today I started learning node.js (need). There is this code on the server

var express = require("express");
var app=express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function (req, res) {
  res.send('Сервер работает');
});

app.get('/chat', function (req, res) {
  res.sendFile(__dirname+"/html/index.html");
  console.log(req.hostname);
});

io.on('connection', function(socket){
  console.log('Присоединился чувак');
});

app.listen(3000, function () {
  console.log('Сервер слушает порт 3000');
});

According to the instructions on the client, the connection should look something like this:
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();
</script>

To which the browser happily tells me
5ce6b028bc4f9129231465.png
The server, of course, does not respond
Folder structure (copied socket.io.js from node_modules/socket.io-client wherever possible)
5ce6b07bd163d458644469.png
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Terentiev, 2019-05-24
@mtix

You need to set permission for your specific domain. This is the CORS policy, that you need to specify a whitelist of domains with which you can work.
https://expressjs.com/en/resources/middleware/cors.html
Set up the origin domain you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question