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?

6
  • do you have any console errors in your browser(frontend)? Commented Jan 9, 2019 at 6: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: stackoverflow.com/questions/4295782/… Commented Jan 9, 2019 at 6:41
  • What version of express do you use? Commented Jan 9, 2019 at 6:49
  • @madalinivascu I currently have no errors in front-end console. Commented Jan 9, 2019 at 7:17
  • @wscourge I currently use Express v. 6.4.1 Commented Jan 9, 2019 at 7:19

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.