Ошибка CORS policy при попытке настройки веб-сокета (socket.io) между node и Vue

Рейтинг: 0Ответов: 1Опубликовано: 15.03.2023

Поднял сервер node с socket.io и хочу подключить к нему фронт на Vue. Оба на одном сервере, node на порту 3000, vue на порту 8080

Когда запускаю, получаю в консоли ошибку

Access to XMLHttpRequest at 'http://172.29.120.182:3000/socket.io/?EIO=3&transport=polling&t=ORcVk2_' from origin 'http://172.29.120.182:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Помогите избиваться от нее и поднять коннект. перерыл гугл и решения подобно этому не меняют ситуацию =(

Код сервера:

const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
const http = require('http')


const port = process.env.PORT || 3000;
const publicPath = path.join(__dirname, "../public")



const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server, {cors: {origin: "*"}});

app.use(express.static(publicPath));

io.on('connection',socket =>{
console.log('Connetced to IO')
socket.on('createMessage', (data) => {
    console.log('Socket message:', data.value)
    socket.emit('newMessage',{
        text:data.value
    })
})
})

server.listen(port,() => {
    console.log(`Started on port ${port}`)

})

Код на фронте:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import components from "@/components/UI";
import VueSocketIO from "vue-3-socket.io";


const app=createApp(App).use(store).use(router).use(new VueSocketIO({
    debug: true,
    connection: 'http://172.29.120.182:3000',
}));


components.forEach(component => {
    app.component(component.name, component);
    })


app.mount('#app')

Ответы

▲ 0

Решил проблему, перестроив конфигурацию сревера:

    const io = require('socket.io')(server, {cors: {
        origin: "http://172.29.120.182:8080",
        methods: ["GET", "POST"],
        allowedHeaders: ["*"],
        transports: ['websocket', 'polling'],
        credentials: true
    },
    allowEIO3: true
});

Одного *cors{origin:"*"} было недостаточно