Socket.io works flawlessly on desktop chrome, chromium and firefox, but not on chrome for android both standard and dev(51).
here's my code:
index.html:
<script src="/socket.io/socket.io.js"></script>
<script type="text/babel" src="scripts/messenger.js"></script>
messenger.js
var socket = io.connect('localhost:3000');
socket.on('chat message ining', (msg) =>
this.iningMessageHandler(JSON.parse(msg))
)
socket.emit('chat message outgoing', JSON.stringify(message));
I've done everything exactly as in official socket.io tutorial. Any ideas what's going on?
Cheers, Wojtek
Socket.io works flawlessly on desktop chrome, chromium and firefox, but not on chrome for android both standard and dev(51).
here's my code:
index.html:
<script src="/socket.io/socket.io.js"></script>
<script type="text/babel" src="scripts/messenger.js"></script>
messenger.js
var socket = io.connect('localhost:3000');
socket.on('chat message ining', (msg) =>
this.iningMessageHandler(JSON.parse(msg))
)
socket.emit('chat message outgoing', JSON.stringify(message));
I've done everything exactly as in official socket.io tutorial. Any ideas what's going on?
Cheers, Wojtek
Share Improve this question asked Apr 14, 2016 at 12:53 Wojciech KulmaWojciech Kulma 6,4463 gold badges20 silver badges28 bronze badges2 Answers
Reset to default 9Well, it looks like you are connecting to localhost:3000
, which might not point to a valid NodeJS server on your phone. Try changing that address to a valid address which has your application running. Also, it's preferable to add the protocol (http://
) to the address.
I think you can't reach your app from your android phone's chrome because of the CORS policy
of the browser. socket.io
tries to connect localhost:3000
but from your phone's browser you have to connect to your local ip something like this: 192.168.x.x
So, the CORS policy stops your connection because these two URL's hosts are not the same.
To solve this issue you can add cors dependency to your app like this:
const app = require('express')();
const cors = require('cors');
app.use(cors());
Or, you can sets the 'Access-Control-Allow-Origin' header like this:
app.options('*', (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
res.send('ok');
});
app.use((req, res) => {
res.set('Access-Control-Allow-Origin', '*');
});