简体   繁体   English

XMLHttpRequest 无法在 ExpressJS 中使用 Socket.io 加载

[英]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. 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.我的客户端连续返回 XMLHttpRequest。 In my server side, I had used在我的服务器端,我使用过

app.use(cors()) app.use(cors())

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

But still no luck.但仍然没有运气。

Client Side running at localhost:6666在 localhost:6666 运行的客户端

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

Server Side running at localhost:5555在 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. XMLHttpRequest 无法加载 localhost:5555/socket.io/?EIO=3&transport=polling&t=LVsapo4。 Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''.凭据标志为“真”,但“访问控制允许凭据”header 为“”。 It must be 'true' to allow credentials.必须为“true”才能允许凭据。 Origin 'localhost:6666' is therefore not allowed access.因此,Origin 'localhost:6666' 不允许访问。

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"]
      }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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