0

I have HTML inputs in my index.html file.

<input type="text" id="handle" >
<input type="text" id="message" >
<button id="send">send</button>

When I fill up data and click send, I want to send them to my node script where I can do something with passed data.

My index.html's script:

$("#send").on("click", function() {
    var message = $("#message").val();
    var handle = $("#handle").val();


    var xhr = new XMLHttpRequest();
    var data = {
        param1: handle,
        param2: message
    };
    xhr.open('POST', '/data');
    xhr.onload = function(data) {
        console.log('loaded', this.responseText);
    };
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify(data));

});

And how I have tried to recieve data in my serverside test.js file.

app.post('/data', function(req, res){

    var obj = {};
    console.log('body: ' + req.body);
    res.send(req.body);

});

In this case, the output shows: body: undefined

How can I send the data from my client side pages to server side so that I can use them to perform my other operations?

  • do you have any console errors in your browser(frontend)? – madalinivascu Jan 09 '19 at 06:28
  • 1
    since you ware using jquery why not use $.ajax( ... also what is is your endpoint doing post .. "/data" ? usully node.js sits on a diffrent port to your normal site if not using it native also see: https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js – taggartJ Jan 09 '19 at 06:41
  • What version of express do you use? – wscourge Jan 09 '19 at 06:49
  • @madalinivascu I currently have no errors in front-end console. –  Jan 09 '19 at 07:17
  • @wscourge I currently use Express v. 6.4.1 –  Jan 09 '19 at 07:19
  • Could you please paste your whole express configuration? I'm interested in all the `app.use()` calls you have. – wscourge Jan 09 '19 at 07:24

1 Answers1

1

You just need to use a JSON body parser in Express like so:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(express.static('./'));
/* Parse JSON data using body parser. */
app.use(bodyParser.json());

app.post('/data', function(req, res){
    console.log('body: ',  req.body);
    res.send(req.body);
});

app.listen(port);

Just do an npm install for this module if not already present:

npm install body-parser
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40