ambelovsky / koa-socket-2

Socket.IO for Koa
https://www.npmjs.com/package/koa-socket-2
98 stars 14 forks source link

Unable to access app.io, app._io in TypeScript, Possible incompatibility with koa-router #17

Open henrymcl opened 5 years ago

henrymcl commented 5 years ago

After switching to koa-socket-2, I don't think I have any way to set up CORS as I cannot io.set('origins', options.frontEnd); with const io = new IO();

app.io, app._io are also not accessible as prompted by TypeScript:

Property 'io' does not exist on type 'import("c:/Users/user/Desktop/ubuntu/koa_ts_react/backend/node_modules/@types/koa/index.d.ts")<any, {}>'.

Full Code:

import * as Koa from 'koa';
import * as fs from 'fs';
import * as path from 'path';
import * as https from 'https';
import * as bodyParser from 'koa-bodyparser';
import * as session from 'koa-session';
import options from './config';

const IO = require('koa-socket-2');

import router from './router';
import sockets from './sockets'

const PORT = 5000;

const sslOptions = {
    key: fs.readFileSync(path.join(__dirname,'ssl','key.pem')),
    cert: fs.readFileSync(path.join(__dirname,'ssl','cert.pem')),
    passphrase: 'Testing'
}

const app = new Koa();
const io = new IO();
app.keys = ['python', 'javascript'];

app.use(session(app));

io.attach(app);

app.use(async (ctx, next) => {
    console.log('\nUSE')
    ctx.set({
        'Access-Control-Allow-Credentials': 'true',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Origin': options.frontEnd,
    });
    await next();
});

const server = https.createServer(sslOptions, app.callback());

app.use(bodyParser({})).use(router.routes()).use(router.allowedMethods());

io.on('connection', sockets);

server.listen(PORT, () => {
    console.log(`listening on ${PORT}`);
});
saviourdog commented 4 years ago

have you find a way to use koa-router with websocket

fluidnotions commented 3 years ago

Read the code and see how to parse options to socket.io it is only one file

/**
        * Options to pass when instantiating socket.io
        * @type <Object>
        * @default {}
        */
       ioOptions: {}