gpt4 book ai didi

node.js - 套接字IO错误 "Access to XMLHttpRequest has been blocked by CORS policy"

转载 作者:太空宇宙 更新时间:2023-11-03 23:50:11 25 4
gpt4 key购买 nike

我的应用程序最近收到错误

"Access to XMLHttpRequest at 'https://my-service-domain/socket.io/?EIO=3&transport=polling&t=M-eWtUQ' from origin 'https://my-app-domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

当我连接到 socket.io 时。我还没有找到解决这个问题的方法,我会详细描述如下图,有没有人遇到过这个错误。

enter image description here

服务器配置:

var express = require('express');
var app = express();

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server, {log:false, origins:'*:*'});

客户端配置:

var socket = io('https://my-service-domain', {transports: ['polling']});
socket.on(channel_id, function(data){
// some code
});

我尝试切换 websocket 连接选项var socket = io('https://my-service-domain', {transports: ['websocket']}),收到错误

"WebSocket connection to 'wss://my-service-domain/socket.io/?EIO=3& transport = websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 "

最佳答案


If you are using Socket.IO v3, you need to explicitly enable Cross-Origin Resource Sharing (CORS).
const io = require("socket.io")(httpServer, {
cors: {
origin: "http://localhost:8080",
methods: ["GET", "POST"]
}
});

httpServer.listen(3000);

关于node.js - 套接字IO错误 "Access to XMLHttpRequest has been blocked by CORS policy",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59749021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com