我正在使用 fetch api 发布和检索用户数据,效果很好,但我也想将 sioket.io 实现到 fetch 中,以从 mysql 数据库发出和广播我选择的数据。
服务器端:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(function(request, result, next) {
result.setHeader("Access-Control-Allow-Origin", "*");
next();
})
dotenv.config({ path: './.env' });
var sqlDatabase = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE,
});
app.set('view engine', 'hbs');
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cookieParser('key cat'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(cors());
const publicDirectory = path.join(__dirname, './public')
app.use(express.static(publicDirectory));
var options = {
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE,
};
var sessionStore = new MySQLStore(options);
app.use(session({
secret: 'key cat',
resave: false,
saveUninitialized: false,
store: sessionStore,
cookie: {
httpOnly: true,
secure: false,
maxAge: 60000
}
}));
app.use(passport.initialize());
app.use(passport.session());
sqlDatabase.connect((err) => {
if (err) {
console.log(err);
} else {
console.log('mysql is connected')
}
});
io.on('connection', (socket) => {
console.log('socket connect successful');
socket.on('new_message', function(results) {
console.log('Client says', results);
})
如果我使用
result.end(JSON.stringify(results));
结果很好,除了我还想发射和广播数据,这就是我使用 sioket.io 的原因。
慕标5832272
相关分类