my code of app.js file is:
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import path from 'path';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import { Server } from 'http';
import { Server as SocketIOServer } from 'socket.io';
const uri='mongodb://localhost:27017/db_pruebas';
const options={
useNewUrlParser:true,
useCreateIndex:true,
useUnifiedTopology: true,
useFindAndModify: false
};
mongoose.Promise=global.Promise;
mongoose.connect(uri,options).then(
()=>{ console.log('conectado a mongo: db_checklist'); },
err=>{console.log('error conectando con mongo:'+err);}
);
const app = express();
app.use(morgan('tiny'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '50mb'}));
const server = new Server(app);
const io = new SocketIOServer(server, {
cors: {
origin: "*",
}
});
app.io = io;
app.use('/api',require('./routes/clientes'));
app.use('/api',require('./routes/sucursales'));
app.use('/api',require('./routes/compras'));
app.use('/api',require('./routes/usuarios'));
app.use('/api',require('./routes/login'));
const history=require('connect-history-api-fallback');
app.use(history());
app.use(express.static(path.join(__dirname,'public')));
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port: ${PORT}`);
});
in code of one example of route use io is:
import express from 'express';
const router=express.Router();
import mongoose from 'mongoose';
import Cliente from '../models/Clientes';
import Notificacion from '../models/Notificaciones';
router.post('/nuevo-cliente', async(req, res)=>{
try{
const body=req.body;
console.log(body);
const Cliente=await Vehiculo.create(body);
if(Cliente){
let bodynofificacion={
'texto':'Nuevo cliente:'+ body.nombre+ ' a las:'+body.fecha,
'activo':1
};
const notificacionDB=await Notificacion.create(bodynofificacion);
req.app.io.emit('new-notification', notificacionDB);
res.status(200).json({
'success':true,
'msg':"chekclist ingresado correctamente",
});
}
}catch(error){
console.log(error)
return res.status(500).json({
mensaje:'Ocurrio un error',
error
})
}
});
module.exports=router;
io
instance for your route to use it – Tengdinvar bsg = require('./routes/test')(app, io)
andmodule.exports = function (app, io) { router.get(...); return router }
– Tengdin