MetinSeylan / Vue-Socket.io

😻 Socket.io implementation for Vuejs and Vuex
https://metin.sh
MIT License
3.95k stars 496 forks source link

Access to XMLHttpRequest at 'http://localhost:3001/socket.io/?EIO=3&transport=polling&t=NSYArA8' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. #301

Open xreider opened 3 years ago

xreider commented 3 years ago

server

const express = require('express')
const app = express()
const server = require('http').createServer(app)
express.json()
express.urlencoded({extended: true})

const io = require('socket.io')(server,
  {
    origins: ["http://localhost:3000"],

    handlePreflightRequest: (req, res) => {
      res.writeHead(200, {
        "Access-Control-Allow-Origin": "http://localhost:3000",
        "Access-Control-Allow-Methods": "GET,POST",
        "Access-Control-Allow-Headers": "my-custom-header",
        "Access-Control-Allow-Credentials": true
      });
      res.end();
    }
  }
)

io.on('connection', socket => {
  console.log('IO connected')
})

module.exports = {
  app, server
}

frontend

import Vue from 'vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'

const options = {
  extraHeaders: {"my-custom-header": 'abas'}
 }

export default function({store}) {
  Vue.use(new VueSocketIO({
    debug: true,
    connection: SocketIO('http://localhost:3001', options),
    // connection: 'http://localhost:3001',
    vuex: {
        store,
        actionPrefix: 'SOCKET_',
        mutationPrefix: 'SOCKET_'
    },
  }))
}

got

Access to XMLHttpRequest at 'http://localhost:3001/socket.io/?EIO=4&transport=polling&t=NSYEGPU' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js?d33e:202 GET http://localhost:3001/socket.io/?EIO=4&transport=polling&t=NSYEGPU net::ERR_FAILED

headers

Request URL: http://localhost:3001/socket.io/?EIO=4&transport=polling&t=NSYDVFS
Request Method: OPTIONS
Status Code: 400 Bad Request
Remote Address: [::1]:3001
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Type: application/json
Date: Wed, 20 Jan 2021 23:51:37 GMT
Keep-Alive: timeout=5
Transfer-Encoding: chunked
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: my-custom-header
Access-Control-Request-Method: GET
Connection: keep-alive
Host: localhost:3001
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 OPR/73.0.3856.344
EIO: 4
transport: polling
t: NSYDVFS
keke599 commented 3 years ago

解决了吗

xreider commented 3 years ago

解决了吗

我过一会分开地试试做API服务器和使用Vue-Socket.io的Nuxt的软件。 现在分开地做了API服务器和使用Nuxt-Socket.io的Nuxt的软件就没问题了!

Tatarmalae commented 3 years ago

https://stackoverflow.com/questions/66047026/socket-io-v3-unsupported-protocol-version-error - allowEIO3: true set server options!!!

ashutosh-roy commented 3 years ago

I have solved the above problem by the following Source Code :

____Server Side Code____

// For Allowing Cross Site Origin Requests
var cors = require('cors'); const app = require('express')();

app.use(cors());

const http = require('http').Server(app); const io = require('socket.io')(http,{ cors:{ origin:"http://localhost:8080", methods: ["GET","POST"], credentials: true, allowEIO3: true }, transport: ['websocket'] });

//Whenever someone connects this gets executed io.on('connection', function(socket) { console.log('A user connected');

//Whenever someone disconnects this piece of code executed socket.on('disconnect', function () { console.log('A user disconnected'); }); });

http.listen(3000, function() { console.log('listening on *:3000'); });

Client Side Code

// Packages For Establishing Socket Connection import SocketIO from 'socket.io-client' import VueSocketIO from 'vue-socket.io'

Vue.use(new VueSocketIO({ debug: true, connection: SocketIO('http://localhost:3000/'), vuex: { store, actionPrefix: 'SOCKET', mutationPrefix: 'SOCKET' }, extraHeaders: { 'Access-Control-Allow-Credentials':true }, allowEIO3:true }))

meroo36 commented 2 years ago
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import VueSocketIO from "vue-socket.io";
import { io } from "socket.io-client";

const socket = io("http://localhost:3000", { transports: ["websocket", "polling", "flashsocket"] });

createApp(App)
    .use(router)
    .use(
        new VueSocketIO({
            debug: true,
            connection: socket,
            //options object is Optional
        })
    )
    .mount("#app");

I passed a transports option like this using socket.io-client and it works.

1129921824 commented 2 years ago

good job

ghandhikus commented 2 years ago

If your backend server uses CORS with auth put in socket options withCredentials: true,. It will just go silent without throwing the error if you use WebSocket as a first transport.