【问题标题】:Meteor and Socket IO - No 'Access-Control-Allow-Origin' header is presentMeteor 和 Socket IO - 不存在“Access-Control-Allow-Origin”标头
【发布时间】:2021-05-05 03:12:28
【问题描述】:

我正在尝试将客户端连接到服务器套接字,但出现此错误。

Access to fetch at 'http://localhost:9999/socket.io/?EIO=4&transport=polling&t=NTQGzyP&b64=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我查看了类似问题的答案并尝试了它们,没有任何变化。这包括使用 WebApp.rawConnectHandlers 设置标题和设置 cors 选项无济于事。我花了很多时间复制其他人提到的不同解决方案,但似乎没有什么不同。

我尝试在创建服务器之前和之后添加标头。

客户

const io = require("socket.io-client")
const socket = io.connect("http://localhost:9999/")

服务器

import {Meteor} from 'meteor/meteor';
import http, * as Http from 'http';
import {Socket} from 'socket.io';
import {WebApp} from "meteor/webapp";

Meteor.startup(() => {

    // Server
    const server: Http.Server = http.createServer();

    WebApp.rawConnectHandlers.use(function (req, res, next) {
        res.setHeader("Access-Control-Allow-Origin", "*");
        return next();
    });

    const io = require('socket.io')(server);

    io.on('connection', (socket: Socket)=>{
        socket.on('hello',(data)=>{
            console.log('HELLO BISH')
            console.log(data.text)
        })
    })


    // Start server
    try {
        server.listen(9999);
    } catch (e) {
        console.error(e);
    }

});

允许连接的正确方法是什么?

【问题讨论】:

    标签: javascript node.js typescript meteor socket.io


    【解决方案1】:

    为了解决这个问题,我必须为套接字设置 cors 配置。我允许http://localhost:3000 连接到它,现在允许我的网页与套接字服务器通信。

    const io = require("socket.io")(server, {
        cors: {
            origin: "http://localhost:3000",
            methods: ["GET", "POST"]
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 2015-08-17
      • 2019-08-15
      • 2017-02-21
      • 2015-09-28
      • 2016-10-30
      • 1970-01-01
      • 2016-07-02
      相关资源
      最近更新 更多