简体   繁体   中英

How to pass data from client side Javascript to node.js using XMLHttpRequest?

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?

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

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