出于好奇,我选择 Koa2 作为我的家庭节点服务器。不幸的是,我被困在为客户端/服务器通信实现 websockets 上。在以下应用程序中,socket.io 客户端拒绝连接到其服务器部分。任何想法/提示?
// main.js
const argv = require('yargs');
const app = require('./src/app');
const conf = require('./config');
const port = argv.port || process.env.PORT || conf.port || 3000;
app.listen(port);
console.log(`IOKvit Server is listening on port ${ port }...`);
.....................
// app.js
const Koa = require('koa');
const mount = require('koa-mount');
const router = require('./api');
const staticRoutes = require('./static');
const app = new Koa();
app.use(mount(staticRoutes));
app.use(router.routes());
app.use(router.allowedMethods());
const http = require('http');
const socket = require('socket.io');
const server = http.createServer(app.callback());
const io = new socket(server);
io.on('connection', function(socket){
console.log('a user connected')
});
module.exports = app;
.....................
// static.js
const Koa = require('koa');
const serve = require('koa-static');
const mount = require('koa-mount');
const path = require('path');
const staticApp = new Koa();
const root_dir = path.dirname(require.main.filename);
staticApp.use(serve(root_dir + '/static', { maxage: 60 * 1000 }));
staticApp.use(mount('/lib/vue', serve(root_dir + '/node_modules/vue/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/vue-material', serve(root_dir + '/node_modules/vue-material/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/vue-router', serve(root_dir + '/node_modules/vue-router/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/socket.io', serve(root_dir + '/node_modules/socket.io-client/dist/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/roboto', serve(root_dir + '/node_modules/roboto-fontface/css/roboto/', { maxage: 60 * 1000 })));
staticApp.use(mount('/lib/material-icons-font', serve(root_dir + '/node_modules/material-icons-font/', { maxage: 60 * 1000 })));
module.exports = staticApp;
.....................
// api.js
const Router = require('koa-router');
const house = require('./house').controller;
const router = new Router();
router.get('/rooms', house.list_rooms);
router.get('/rooms/:name', house.room);
module.exports = router;