简体   繁体   中英

XMLHttpRequest cannot load with Socket.io in ExpressJS

I am currently using Socket.io npm module running with ExpressJS in my server at port 5555. In my client side, I am using io.connect to my localhost:5555 which is my server inside AngularJS controller. My client side returns XMLHttpRequest continuously. In my server side, I had used

app.use(cors())

app.use(cors(" http://localhost:6666 "))

But still no luck.

Client Side running at localhost:6666

var socket = io.connect("http://localhost:5555");

Server Side running at localhost:5555

var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT;
io.set('transports', ['websocket', 'xhr-polling', 'jsonp-polling', 'htmlfile', 'flashsocket']);
io.set('origins', '*:*');

Error Message:

XMLHttpRequest cannot load localhost:5555/socket.io/?EIO=3&transport=polling&t=LVsapo4. Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'localhost:6666' is therefore not allowed access.

Can you try this in your express server code

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

instead of the code that you are currently using.

Please try this and see if it works

var express = require('express');
var app = express();
var httpServer = require('http').Server(app);
    const io = require("socket.io")(httpServer, {
      cors: {
        origin: "https://example.com",
        methods: ["GET", "POST"]
      }
    });

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