D
D
dolen2282020-03-01 14:43:37
JavaScript
dolen228, 2020-03-01 14:43:37

Why doesn't CORS socket io + express work on now sh?

Hello, socket io is not working.

Here is the error:

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


Here is the code:

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);
        })
    })
});


help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-03-01
@HistoryART

You had to specify a stupid link or * for a valid or valid resource, and you all methods from Google zafigachit ahaha) Look in the documentation, I honestly see this cors for the second time, but I cut it as described above and everything is ok.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question