最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Socket.io doesn't work on android chrome 51 - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 9

Well, 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', '*');
});
发布评论

评论列表(0)

  1. 暂无评论