Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

234
Vistas
Communication between inline JavaScript and Node.js

I am using Node.js and I want to send a request which contains an input value to the server when a button is pressed.

So here's my HTML code :

<!DOCTYPE html>

<html>
    <head>
        <meta charset="utf-8">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>

    <body>
        <input id="input" action="/onclick" autocomplete="off">
        <button id="button">Send</button>
        <script>
            let input = document.getElementById('input');

            document.getElementById('button').addEventListener('click', (event) => {
                event.preventDefault();
                let value = input.value;

                if (value) {
                    let data = {};
                    data.title = 'getValue',
                    data.message = value;

                    $.ajax({
                        url:'/onclick',
                        data: JSON.stringify(data),
                        type: 'POST',
                        success: (responseData) => {
                            console.log('Success!');
                        },
                    });

                    input.value = null;
                }
            });
        </script>
    </body>
</html>

And here's my server.js :

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.post('/onclick', (req, res) => {
    console.log('body: '+ JSON.stringify(req.message));
    res.send(req.message);
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

The code doesn't throw any error (it returns Success! in browser console) but the problem is that in the Node.js shell it sends body: undefined instead of the input value.

Do you know how to fix that ?

Thanks in advance,

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Add this line in your server.js to access the request body:

app.use(express.json());

And use req.body instead of req.message to access the request body

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda