I'm running a nodejs socket.io server on a raspberry pi, and a socket.io web client on Firefox.
But Firefox keeps giving me a Cross-Origin Request Blocked (Same Origin Policy Error).
// nodeJS Server:
var app = require('express')();
var cors = require('cors');
app.use(cors({origin: '*:*'}));
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.on('connection', function(socket) {
socket.emit('announcements', { message: 'A new user jas joined!' });
});
//JS Browser client:
const socket = io('ws://<INSERT_MY_EXTERNAL_IP>:3000');
socket.on('connect', () => {
socket.send('Hello!');
});
I've also tried: io.origins(...), io.set("origin", ...), but those keep saying the functions origins and set are undefined.
Not sure what to do at this point.
You can pass in a cors
prop when you initialize the server socket.
Pass in a config object with cors
set to true
, eg. cors: true
or cors: { origin: '*' }
.
Read more about thathere .
In action (only tested in LAN):
client.js
const socket = io('ws://localhost:3000');
socket.on('testing', res => { console.log(res) });
server.js
const app = require('express')()
const server = require('http').createServer(app)
const opts = { cors: { origin: '*' } }
const io = require('socket.io')(server, opts)
const cors = require('cors')
app.use(cors())
io.on('connection', (socket) => {
console.log(`Client connected (id=${socket.id})`)
socket.emit('testing', 123)
socket.on('disconnect', () => {
console.log(`Client disconnected (id=${socket.id})`)
})
});
(
port => server.listen(
port,
() => console.log(`Express server running on port ${port}`)
)
)(3000)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.