@dolen228

Почему не работает CORS socket io + express на now sh?

Здравствуйте, не работает socket io.

Вот ошибка:

Access to XMLHttpRequest at 'https://ufcbot-server.now.sh/socket.io/?EIO=3&transport=polling&t=N2Lw0f1' from origin 'https://ufcbot.now.sh' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js:267 GET https://ufcbot-server.now.sh/socket.io/?EIO=3&transport=polling&t=N2Lw0f1 net::ERR_FAILED


Вот код:

const pool = require(`./db`)

const express = require(`express`);
const app = require(`express`)();
const server = require(`https`).createServer(app);
const io = require('socket.io')(server, {
    log: false,
    agent: false,
    origins: '*:*',
    transports: ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling', 'polling']
});
const cors = require(`cors`)

app.use(cors({
    origin: true,
    methods: ["GET", "POST"]
}));

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.header('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', false);

    // Pass to next layer of middleware
    next();
});

app.use(express.static(`public`));
server.listen(8000);

io.on('connection', (client) => {
    client.on('getRows', (id) => {
        pool.query(`SELECT * FROM users WHERE uid = ${id}`, (err, res) => {
            if (err) throw err;
            client.emit(`rowsData`, res);
        })
    });

    client.on(`createAccount`, (uid) => {
        pool.query(`INSERT INTO users (uid) VALUES (${uid})`, (err, res) => {
            if (err) throw err;
            client.emit(`createAccountData`, res);
        })
    })
});


Помогите пожалуйста
  • Вопрос задан
  • 2758 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы