Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!