简体   繁体   中英

Cannot connect to socket.io server: Cross-origin request blocked

This is a nodejs server:

var express = require('express');
var app = express();
app.use(express.static('public'));
const server = require('http').createServer(app);
server.listen(1437, function(){
  console.log('https and websocket listening on *:1437');
});

The client is:

var socketOptions = {
    secure: true,
    reconnection: true,
    reconnectionDelay: 1000,
    timeout: 15000,
    pingTimeout: 15000,
    pingInterval: 45000,
    query: {
        framespersecond: frameRate,
        audioBitrate: audioRate
    }
};

socket = io.connect('https://localhost:1437', socketOptions);

After I run node server.js I check that the server correctly starts.

But when I run the page where the client is, this error is shown in developer console:

Cross-origin request blocked: The same origin policy does not allow reading of remote resources at https://localhost:1437/socket.io/?Framespersecond=15&audioBitrate=22050&EIO=3&transport=polling&t=NJDLua7. (Reason: CORS request not successful)

How can I solve it? currently, this is my development machine. When I deploy the web page in production, will I just need to change localhost by the remote server name?

This is package.json of the server:

{
  "name": "rtc2rtmp",
  "version": "1.0.0",
  "description": "mediarecorder -> websocket -> rtmp",
  "dependencies": {
    "express": "^4.17.1",
    "fluent-ffmpeg": "^2.1.2",
    "socket.io": "^2.3.0"
  }
}

And nodejs version is 14.12.0

The cross origin issue is caused by socket.io's attempt to first connect on regular http before it tries to make a webSocket connection. You can tell it to just go directly to the webSocket connection which is not subject to the cross origin restrictions by adding this:

transports: ['websocket']

to your client-side socket options and you will avoid the cross origin issue entirely since webSocket connections are not subject to cross origin restrictions.

The other alternative it to enable cross origin requests from this origin on your express server, but if you don't really need the non-webSocket transport support, then just telling the client to start out directly with a webSocket connection is easier.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM