【问题标题】:How can I fix this CORS with Socket.io?如何使用 Socket.io 修复这个 CORS?
【发布时间】:2020-08-03 00:39:56
【问题描述】:

我在使用 Socket.io 将本地托管的聊天应用程序迁移到我的实时云服务器时遇到问题。我知道那里有解决方案,但是,我找不到任何可以解决我的问题的方法。

我收到“跨域请求被阻止:同源策略不允许在...读取远程资源(原因:CORS 请求未成功)” '''

const io = require('socket.io')(3000)

io.on('connection', socket => {
    socket.on('new-user', name => {
        users[socket.id] = name
        socket.broadcast.emit('user-connected', name)
    })
    socket.on('send-chat-message', message => {
        socket.broadcast.emit('chat-message', {message: message, name: 
            users[socket.id]})
    })
    socket.on('disconnect', () => {
        socket.broadcast.emit('user-disconnected', users[socket.id])
       delete users[socket.id]

    })  

}) 

上面是 server.js 文件。

    const socket = io('<url>:3000')
    const messageForm = document.getElementById('send-container')
    const messageInput = document.getElementById('message-input')
    const messageContainer = document.getElementById('message-container')

这是我的应用程序正在使用的脚本,被我的替换了,它只是在这里被屏蔽了。

我尝试过的事情:

  • 在我的 Apache 和 Nginx 配置中使用“Header set Access-Control-Allow-Origin”设置标头
  • 更改脚本上的网址
  • 更改端口

到目前为止我没有运气,请帮助我!

【问题讨论】:

    标签: html node.js web socket.io cors


    【解决方案1】:

    试试

    // Allow all origins
    io.origins('*');
    

    source

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2021-08-25
      • 2012-12-15
      • 2021-10-11
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2021-03-21
      相关资源
      最近更新 更多