简体   繁体   中英

Using DOM events in nodeJS and express

I'm trying to catch a DOM event with nodeJS and express. I have read something about "socket.io" module but I'm not able to use it correctly.

I'm trying to execute some code when when a "file input" changes it's content in the DOM.

<div class="input-group">
 <div class="custom-file">
  <input type="file" name="image" class="custom-file-input form-control" id="inputGroupFile02"
   aria-describedby="inputGroupFileAddon02">
  <label class="custom-file-label" for="inputGroupFile02">Choose file</label>
 </div>
</div>

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
    var socket = io();;
    $( "#inputGroupFileAddon02" ).change(function(e) {
        e.preventDefault();
        socket.emit('cambio_imagen_profile_edit', "Cambiando la imagen");
        return false;
    });
  });
</script>

This is my express server configuration, it's correct the socket.io configuration?:

const express = require('express');
const http = require("http");
const io = require('socket.io')(http);

const app = express();
const httpServer = http.createServer(app);
app.set('port', process.env.PORT || 4001);

httpServer.listen(app.get('port'), () =>
    console.log('Inicializando servidor en el puerto ', app.get('port'), ' !!!')
)

io.on('connection', (socket) => {
    console.log('socket connected');
    socket.on('cambio_imagen_profile_edit', (msg) => {
      console.log('message: ' + msg);
    });
  });

I need to make an "on change" event on "inputGroupFile02" element. Someone knows about it?

Thanks for reading!

On the backend side you have to define the event handlers for incoming messages from the sockets.

const express = require('express');
const http = require("http");
const app = express();
const httpServer = http.createServer(app);
const io = require('socket.io')(httpServer );

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('message', (msg) => {
    // handle the msg here
    console.log('message: ' + msg);
  });
});

And add the event on the frontend side that will send information about the change of the input element

<script>
    $(function () {
        var socket = io();
        $("#inputGroupFile02").change(function (e) {
            e.preventDefault();
            socket.emit('cambio_imagen_profile_edit', "Cambiando la imagen");
        });
    });
</script>

Just modify the function so it broadcast the information you want backend server to receive and call it onChange event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM