cors策略已阻止对xmlhttprequest到socket.io的访问:无“访问控制允许源”

mm9b1k5b  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(202)

我正在尝试连接端口3007上的插座,而前端在端口3008上提供服务,我曾尝试使用cors,但没有成功。我一直在'http://localhost:3007/socket.io/?eio=4&transport=polling&t=nheaijp“起源”http://localhost:3008'已被cors策略阻止:请求的资源上不存在'access control allow origin'标头。

const socket = require('socket.io')
const cors = require('cors')
app.use(cors())
const PORT = process.env.PORT
const server = app.listen(PORT, function () {
    console.log ("up and running on port: "+PORT)
})

const io = socket(server,{
    cors: {
      origin: ['*'],
      handlePreflightRequest: (req,res)=>{
        res.writeHead(200,{
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
            'Access-Control-Allow-Headers': 'my-custom-header',
            'Access-Control-Allow-Credentials': true,
        })
      }
    }
  })

io.on('connection', function (socket) {
    socket.on('newOrder', function () {
        io.sockets.emit('newOrder')
    })
    socket.on('setOrderReady', function (driverId) {
        io.sockets.emit('setOrderReady', driverId)
    })
})

我也试过这个

const socket = require('socket.io')
const cors = require('cors')
app.use(cors())
const PORT = process.env.PORT
const server = app.listen(PORT, function () {
    console.log ("up and running on port: "+PORT)
})

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

io.on('connection', function (socket) {
    socket.on('newOrder', function () {
        io.sockets.emit('newOrder')
    })
    socket.on('setOrderReady', function (driverId) {
        io.sockets.emit('setOrderReady', driverId)
    })
})

但还是一样的问题

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题